blob: eeaac44e394009948352af1f4ca6bf35cc026782 [file] [log] [blame]
Adrian Ludwig24359402011-11-07 09:24:23 -08001page.title=Designing for Security
2@jd:body
3
4<div id="qv-wrapper">
5<div id="qv">
6<h2>In this document</h2>
7<ol>
8<li><a href="#Dalvik">Using Davlik Code</a></li>
9<li><a href="#Native">Using Native Code</a></li>
10<li><a href="#Data">Storing Data</a></li>
11<li><a href="#IPC">Using IPC</a></li>
12<li><a href="#Permissions">Using Permissions</a></li>
13<li><a href="#Networking">Using Networking</a></li>
14<li><a href="#DynamicCode">Dynamically Loading Code</a></li>
15<li><a href="#Input">Performing Input Validation</a></li>
16<li><a href="#UserData">Handling User Data</a></li>
17<li><a href="#Crypto">Using Cryptography</a></li>
18</ol>
19<h2>See also</h2>
20<ol>
21<li><a href="http://source.android.com/tech/security/index.html">Android
22Security Overview</a></li>
23<li><a href="{@docRoot}guide/topics/security/security.html">Android Security
24And Permissions</a></li>
25</ol>
26</div></div>
27<p>Android was designed so that most developers will be able to build
28applications using the default settings and not be confronted with difficult
29decisions about security. Android also has a number of security features built
30into the operating system that significantly reduce the frequency and impact of
31application security issues.</p>
32
33<p>Some of the security features that help developers build secure applications
34include:
35<ul>
36<li>The Android Application Sandbox that isolates data and code execution on a
37per-application basis.</li>
38<li>Android application framework with robust implementations of common
39security functionality such as cryptography, permissions, and secure IPC.</li>
40<li>Technologies like ASLR, NX, ProPolice, safe_iop, OpenBSD dlmalloc, OpenBSD
41calloc, and Linux mmap_min_addr to mitigate risks associated with common memory
42management errors</li>
43<li>An encrypted filesystem that can be enabled to protect data on lost or
44stolen devices.</li>
45</ul></p>
46
47<p>Nevertheless, it is important for developers to be familiar with Android
48security best practices to make sure they take advantage of these capabilities
49and to reduce the likelihood of inadvertently introducing security issues that
50can affect their applications.</p>
51
52<p>This document is organized around common APIs and development techniques
53that can have security implications for your application and its users. As
54these best practices are constantly evolving, we recommend you check back
55occasionally throughout your application development process.</p>
56
57<a name="Dalvik"></a>
58<h2>Using Dalvik Code</h2>
59<p>Writing secure code that runs in virtual machines is a well-studied topic
60and many of the issues are not specific to Android. Rather than attempting to
61rehash these topics, we’d recommend that you familiarize yourself with the
62existing literature. Two of the more popular resources are:
63<ul>
64<li><a href="http://www.securingjava.com/toc.html">
65http://www.securingjava.com/toc.html</a></li>
66<li><a
67href="https://www.owasp.org/index.php/Java_Security_Resources">
68https://www.owasp.org/index.php/Java_Security_Resources</a></li>
69</ul></p>
70
71<p>This document is focused on the areas which are Android specific and/or
72different from other environments. For developers experienced with VM
73programming in other environments, there are two broad issues that may be
74different about writing apps for Android:
75<ul>
76<li>Some virtual machines, such as the JVM or .net runtime, act as a security
77boundary, isolating code from the underlying operating system capabilities. On
78Android, the Dalvik VM is not a security boundary -- the application sandbox is
79implemented at the OS level, so Dalvik can interoperate with native code in the
80same application without any security constraints.</li>
81<li>Given the limited storage on mobile devices, it’s common for developers
82to want to build modular applications and use dynamic class loading. When
83doing this consider both the source where you retrieve your application logic
84and where you store it locally. Do not use dynamic class loading from sources
85that are not verified, such as unsecured network sources or external storage,
86since that code can be modified to include malicious behavior.</li>
87</ul></p>
88
89<a name="Native"></a>
90<h2>Using Native Code</h2>
91
92<p>In general, we encourage developers to use the Android SDK for most
93application development, rather than using native code. Applications built
94with native code are more complex, less portable, and more like to include
95common memory corruption errors such as buffer overflows.</p>
96
97<p>Android is built using the Linux kernel and being familiar with Linux
98development security best practices is especially useful if you are going to
99use native code. This document is too short to discuss all of those best
100practices, but one of the most popular resources is “Secure Programming for
101Linux and Unix HOWTO”, available at <a
102href="http://www.dwheeler.com/secure-programs">
103http://www.dwheeler.com/secure-programs</a>.</p>
104
105<p>An important difference between Android and most Linux environments is the
106Application Sandbox. On Android, all applications run in the Application
107Sandbox, including those written with native code. At the most basic level, a
108good way to think about it for developers familiar with Linux is to know that
109every application is given a unique UID with very limited permissions. This is
110discussed in more detail in the <a
111href="http://source.android.com/tech/security/index.html">Android Security
112Overview</a> and you should be familiar with application permissions even if
113you are using native code.</p>
114
115<a name="Data"></a>
116<h2>Storing Data</h2>
117
118<h3>Using internal files</h3>
119
120<p>By default, files created on <a
121href="{@docRoot}guide/topics/data/data-storage.html#filesInternal">internal
122storage</a> are only accessible to the application that created the file. This
123protection is implemented by Android and is sufficient for most
124applications.</p>
125
126<p>Use of <a
127href="{@docRoot}reference/android/content/Context.html#MODE_WORLD_WRITEABLE">
128world writable</a> or <a
Scott Maincd1b08e2011-12-27 16:22:27 -0800129href="{@docRoot}reference/android/content/Context.html#MODE_WORLD_READABLE">world
130readable</a> files for IPC is discouraged because it does not provide
Adrian Ludwig24359402011-11-07 09:24:23 -0800131the ability to limit data access to particular applications, nor does it
132provide any control on data format. As an alternative, you might consider using
133a ContentProvider which provides read and write permissions, and can make
134dynamic permission grants on a case-by-case basis.</p>
135
136<p>To provide additional protection for sensitive data, some applications
137choose to encrypt local files using a key that is not accessible to the
138application. (For example, a key can be placed in a <code><a
139href={@docRoot}reference/java/security/KeyStore.html">KeyStore</a></code> and
140protected with a user password that is not stored on the device). While this
141does not protect data from a root compromise that can monitor the user
142inputting the password, it can provide protection for a lost device without <a
143href="http://source.android.com/tech/encryption/index.html">file system
144encryption</a>.</p>
145
146<h3>Using external storage</h3>
147
148<p>Files created on <a
149href="{@docRoot}guide/topics/data/data-storage.html#filesExternal">external
150storage</a>, such as SD Cards, are globally readable and writable. Since
151external storage can be removed by the user and also modified by any
152application, applications should not store sensitive information using
153external storage.</p>
154
155<p>As with data from any untrusted source, applications should perform input
156validation when handling data from external storage (see Input Validation
157section). We strongly recommend that applications not store executables or
158class files on external storage prior to dynamic loading. If an application
159does retrieve executable files from external storage they should be signed and
160cryptographically verified prior to dynamic loading.</p>
161
162<h3>Using content providers</h3>
163
164<p>ContentProviders provide a structured storage mechanism that can be limited
165to your own application, or exported to allow access by other applications. By
166default, a <code>
167<a href="{@docRoot}reference/android/content/ContentProvider.html">
168ContentProvider</a></code> is
169<a href="{@docRoot}guide/topics/manifest/provider-element.html#exported">exported
170</a> for use by other applications. If you do not intend to provide other
171applications with access to your<code>
172<a href="{@docRoot}reference/android/content/ContentProvider.html">
173ContentProvider</a></code>, mark them as <code><a
174href="{@docRoot}guide/topics/manifest/provider-element.html#exported">
175android:exported=false</a></code> in the application manifest.</p>
176
177<p>When creating a <code>
178<a href="{@docRoot}reference/android/content/ContentProvider.html">ContentProvider
179</a></code> that will be exported for use by other applications, you can specify
180a single
181<a href="{@docRoot}guide/topics/manifest/provider-element.html#prmsn">permission
182</a> for reading and writing, or distinct permissions for reading and writing
183within the manifest. We recommend that you limit your permissions to those
184required to accomplish the task at hand. Keep in mind that it’s usually
185easier to add permissions later to expose new functionality than it is to take
186them away and break existing users.</p>
187
188<p>If you are using a <code>
189<a href="{@docRoot}reference/android/content/ContentProvider.html">
190ContentProvider</a></code> for sharing data between applications built by the
191same developer, it is preferable to use
192<a href="{@docRoot}guide/topics/manifest/permission-element.html#plevel">signature
193level permissions</a>. Signature permissions do not require user confirmation,
194so they provide a better user experience and more controlled access to the
195<code>
196<a href="{@docRoot}reference/android/content/ContentProvider.html">
197ContentProvider</a></code>.</p>
198
199<p>ContentProviders can also provide more granular access by declaring the <a
200href="{@docRoot}guide/topics/manifest/provider-element.html#gprmsn">
201grantUriPermissions</a> element and using the <code><a
Scott Maincd1b08e2011-12-27 16:22:27 -0800202href="{@docRoot}reference/android/content/Intent.html#FLAG_GRANT_READ_URI_PERMISSION">FLAG_GRANT_READ_URI_PERMISSION</a></code>
203and <code><a
204href="{@docRoot}reference/android/content/Intent.html#FLAG_GRANT_WRITE_URI_PERMISSION">FLAG_GRANT_WRITE_URI_PERMISSION</a></code>
205flags in the Intent object
Adrian Ludwig24359402011-11-07 09:24:23 -0800206that activates the component. The scope of these permissions can be further
207limited by the <code><a
208href="{@docRoot}guide/topics/manifest/grant-uri-permission-element.html">
209grant-uri-permission element</a></code>.</p>
210
211<p>When accessing a <code>
212<a href="{@docRoot}reference/android/content/ContentProvider.html">
213ContentProvider</a></code>, use parameterized query methods such as <code>
Scott Maincd1b08e2011-12-27 16:22:27 -0800214<a href="{@docRoot}reference/android/content/ContentProvider.html#query(android.net.Uri,%20java.lang.String[],%20java.lang.String,%20java.lang.String[],%20java.lang.String)">query()</a></code>, <code><a
215href="{@docRoot}reference/android/content/ContentProvider.html#update(android.net.Uri,%20android.content.ContentValues,%20java.lang.String,%20java.lang.String[])">update()</a></code>, and <code><a
216href="{@docRoot}reference/android/content/ContentProvider.html#delete(android.net.Uri,%20java.lang.String,%20java.lang.String[])">delete()</a></code> to avoid
Adrian Ludwig24359402011-11-07 09:24:23 -0800217potential <a href="http://en.wikipedia.org/wiki/SQL_injection">SQL
218Injection</a> from untrusted data. Note that using parameterized methods is not
219sufficient if the <code>selection</code> is built by concatenating user data
220prior to submitting it to the method.</p>
221
222<p>Do not have a false sense of security about the write permission. Consider
223that the write permission allows SQL statements which make it possible for some
224data to be confirmed using creative <code>WHERE</code> clauses and parsing the
225results. For example, an attacker might probe for presence of a specific phone
226number in a call-log by modifying a row only if that phone number already
227exists. If the content provider data has predictable structure, the write
228permission may be equivalent to providing both reading and writing.</p>
229
230<a name="IPC"></a>
231<h2>Using Interprocess Communication (IPC)</h2>
232
233<p>Some Android applications attempt to implement IPC using traditional Linux
234techniques such as network sockets and shared files. We strongly encourage the
235use of Android system functionality for IPC such as Intents, Binders, Services,
236and Receivers. The Android IPC mechanisms allow you to verify the identity of
237the application connecting to your IPC and set security policy for each IPC
238mechanism.</p>
239
240<p>Many of the security elements are shared across IPC mechanisms. <a
241href="{@docRoot}reference/android/content/BroadcastReceiver.html">
242Broadcast Receivers</a>, <a
243href="{@docRoot}reference/android/R.styleable.html#AndroidManifestActivity">
244Activities</a>, and <a
245href="{@docRoot}reference/android/R.styleable.html#AndroidManifestService">
246Services</a> are all declared in the application manifest. If your IPC mechanism is
Scott Maincd1b08e2011-12-27 16:22:27 -0800247not intended for use by other applications, set the <a
248href="{@docRoot}guide/topics/manifest/service-element.html#exported">{@code android:exported}</a>
249property to false. This is useful for applications that consist of multiple processes
Adrian Ludwig24359402011-11-07 09:24:23 -0800250within the same UID, or if you decide late in development that you do not
251actually want to expose functionality as IPC but you don’t want to rewrite
252the code.</p>
253
254<p>If your IPC is intended to be accessible to other applications, you can
255apply a security policy by using the <a
256href="{@docRoot}reference/android/R.styleable.html#AndroidManifestPermission">
257Permission</a> tag. If IPC is between applications built by the same developer,
258it is preferable to use <a
259href="{@docRoot}guide/topics/manifest/permission-element.html#plevel">signature
260level permissions</a>. Signature permissions do not require user confirmation,
261so they provide a better user experience and more controlled access to the IPC
262mechanism.</p>
263
264<p>One area that can introduce confusion is the use of intent filters. Note
265that Intent filters should not be considered a security feature -- components
266can be invoked directly and may not have data that would conform to the intent
267filter. You should perform input validation within your intent receiver to
268confirm that it is properly formatted for the invoked receiver, service, or
269activity.</p>
270
271<h3>Using intents</h3>
272
273<p>Intents are the preferred mechanism for asynchronous IPC in Android.
274Depending on your application requirements, you might use <code><a
Scott Maincd1b08e2011-12-27 16:22:27 -0800275href="{@docRoot}reference/android/content/Context.html#sendBroadcast(android.content.Intent)">sendBroadcast()</a></code>,
276<code><a
277href="{@docRoot}reference/android/content/Context.html#sendOrderedBroadcast(android.content.Intent,%20java.lang.String)">sendOrderedBroadcast()</a></code>,
278or direct an intent to a specific application component.</p>
Adrian Ludwig24359402011-11-07 09:24:23 -0800279
280<p>Note that ordered broadcasts can be “consumed” by a recipient, so they
281may not be delivered to all applications. If you are sending an Intent where
282delivery to a specific receiver is required, the intent must be delivered
283directly to the receiver.</p>
284
285<p>Senders of an intent can verify that the recipient has a permission
286specifying a non-Null Permission upon sending. Only applications with that
287Permission will receive the intent. If data within a broadcast intent may be
288sensitive, you should consider applying a permission to make sure that
289malicious applications cannot register to receive those messages without
290appropriate permissions. In those circumstances, you may also consider
291invoking the receiver directly, rather than raising a broadcast.</p>
292
293<h3>Using binder and AIDL interfaces</h3>
294
295<p><a href="{@docRoot}reference/android/os/Binder.html">Binders</a> are the
296preferred mechanism for RPC-style IPC in Android. They provide a well-defined
297interface that enables mutual authentication of the endpoints, if required.</p>
298
299<p>We strongly encourage designing interfaces in a manner that does not require
300interface specific permission checks. Binders are not declared within the
301application manifest, and therefore you cannot apply declarative permissions
302directly to a Binder. Binders generally inherit permissions declared in the
303application manifest for the Service or Activity within which they are
304implemented. If you are creating an interface that requires authentication
305and/or access controls on a specific binder interface, those controls must be
306explicitly added as code in the interface.</p>
307
308<p>If providing an interface that does require access controls, use <code><a
Scott Maincd1b08e2011-12-27 16:22:27 -0800309href="{@docRoot}reference/android/content/Context.html#checkCallingPermission(java.lang.String)">checkCallingPermission()</a></code>
310to verify whether the
Adrian Ludwig24359402011-11-07 09:24:23 -0800311caller of the Binder has a required permission. This is especially important
312before accessing a Service on behalf of the caller, as the identify of your
313application is passed to other interfaces. If invoking an interface provided
314by a Service, the <code><a
Scott Maincd1b08e2011-12-27 16:22:27 -0800315href="{@docRoot}reference/android/content/Context.html#bindService(android.content.Intent,%20android.content.ServiceConnection,%20int)">bindService()</a></code>
Adrian Ludwig24359402011-11-07 09:24:23 -0800316 invocation may fail if you do not have permission to access the given Service.
317 If calling an interface provided locally by your own application, it may be
318useful to use the <code><a
319href="{@docRoot}reference/android/os/Binder.html#clearCallingIdentity()">
320clearCallingIdentity()</a></code> to satisfy internal security checks.</p>
321
322<h3>Using broadcast receivers</h3>
323
324<p>Broadcast receivers are used to handle asynchronous requests initiated via
325an intent.</p>
326
327<p>By default, receivers are exported and can be invoked by any other
328application. If your <code><a
Scott Maincd1b08e2011-12-27 16:22:27 -0800329href="{@docRoot}reference/android/content/BroadcastReceiver.html">
Adrian Ludwig24359402011-11-07 09:24:23 -0800330BroadcastReceivers</a></code> is intended for use by other applications, you
331may want to apply security permissions to receivers using the <code><a
Scott Maincd1b08e2011-12-27 16:22:27 -0800332href="{@docRoot}guide/topics/manifest/receiver-element.html">
Adrian Ludwig24359402011-11-07 09:24:23 -0800333&lt;receiver&gt;</a></code> element within the application manifest. This will
334prevent applications without appropriate permissions from sending an intent to
335the <code><a
Scott Maincd1b08e2011-12-27 16:22:27 -0800336href="{@docRoot}reference/android/content/BroadcastReceiver.html">
Adrian Ludwig24359402011-11-07 09:24:23 -0800337BroadcastReceivers</a></code>.</p>
338
339<h3>Using Services</h3>
340
341<p>Services are often used to supply functionality for other applications to
342use. Each service class must have a corresponding <service> declaration in its
343package's AndroidManifest.xml.</p>
344
345<p>By default, Services are exported and can be invoked by any other
Scott Maincd1b08e2011-12-27 16:22:27 -0800346application. Services can be protected using the <a
347href="{@docRoot}guide/topics/manifest/service-element.html#prmsn">{@code android:permission}</a>
348attribute
Adrian Ludwig24359402011-11-07 09:24:23 -0800349within the manifest’s <code><a
Scott Maincd1b08e2011-12-27 16:22:27 -0800350href="{@docRoot}guide/topics/manifest/service-element.html">
Adrian Ludwig24359402011-11-07 09:24:23 -0800351&lt;service&gt;</a></code> tag. By doing so, other applications will need to declare
352a corresponding <code><a
Scott Maincd1b08e2011-12-27 16:22:27 -0800353href="{@docRoot}guide/topics/manifest/uses-permission-element.html">&lt;uses-permission&gt;</a>
354</code> element in their own manifest to be
Adrian Ludwig24359402011-11-07 09:24:23 -0800355able to start, stop, or bind to the service.</p>
356
357<p>A Service can protect individual IPC calls into it with permissions, by
358calling <code><a
Scott Maincd1b08e2011-12-27 16:22:27 -0800359href="{@docRoot}reference/android/content/Context.html#checkCallingPermission(java.lang.String)">checkCallingPermission()</a></code>
360before executing
Adrian Ludwig24359402011-11-07 09:24:23 -0800361the implementation of that call. We generally recommend using the
362declarative permissions in the manifest, since those are less prone to
363oversight.</p>
364
365<h3>Using Activities</h3>
366
367<p>Activities are most often used for providing the core user-facing
368functionality of an application. By default, Activities are exported and
369invokable by other applications only if they have an intent filter or binder
370declared. In general, we recommend that you specifically declare a Receiver or
371Service to handle IPC, since this modular approach reduces the risk of exposing
372functionality that is not intended for use by other applications.</p>
373
374<p>If you do expose an Activity for purposes of IPC, the <code><a
Scott Maincd1b08e2011-12-27 16:22:27 -0800375href="{@docRoot}guide/topics/manifest/activity-element.html#prmsn">android:permission</a></code>
376attribute in the <code><a
377href="{@docRoot}guide/topics/manifest/activity-element.html">
Adrian Ludwig24359402011-11-07 09:24:23 -0800378&lt;activity&gt;</a></code> declaration in the application manifest can be used to
379restrict access to only those applications which have the stated
380permissions.</p>
381
382<a name="Permissions"></a>
383<h2>Using Permissions</h2>
384
385<h3>Requesting Permissions</h3>
386
387<p>We recommend minimizing the number of permissions requested by an
388application. Not having access to sensitive permissions reduces the risk of
389inadvertently misusing those permissions, can improve user adoption, and makes
390applications less attractive targets for attackers.</p>
391
392<p>If it is possible to design your application in a way that does not require
393a permission, that is preferable. For example, rather than requesting access
394to device information to create an identifier, create a <a
395href="{@docRoot}reference/java/util/UUID.html">GUID</a> for your application.
396(This specific example is also discussed in Handling User Data) Or, rather than
397using external storage, store data in your application directory.</p>
398
399<p>If a permission is not required, do not request it. This sounds simple, but
400there has been quite a bit of research into the frequency of over-requesting
401permissions. If you’re interested in the subject you might start with this
402research paper published by U.C. Berkeley: <a
403href="http://www.eecs.berkeley.edu/Pubs/TechRpts/2011/EECS-2011-48.pdf">
404http://www.eecs.berkeley.edu/Pubs/TechRpts/2011/EECS-2011-48.pdf</a></p>
405
406<p>In addition to requesting permissions, your application can use <a
407href="{@docRoot}guide/topics/manifest/permission-element.html">permissions</a>
408to protect IPC that is security sensitive and will be exposed to other
409applications -- such as a <code><a
410href="{@docRoot}reference/android/content/ContentProvider.html">
411ContentProvider</a></code>. In general, we recommend using access controls
412other than user confirmed permissions where possible since permissions can
413be confusing for users. For example, consider using the <a
414href="{@docRoot}guide/topics/manifest/permission-element.html#plevel">signature
415protection level</a> on permissions for IPC communication between applications
416provided by a single developer.</p>
417
418<p>Do not cause permission re-delegation. This occurs when an app exposes data
419over IPC that is only available because it has a specific permission, but does
420not require that permission of any clients of it’s IPC interface. More
421details on the potential impacts, and frequency of this type of problem is
422provided in this research paper published at USENIX: <a
423href="http://www.cs.berkeley.edu/~afelt/felt_usenixsec2011.pdf">http://www.cs.be
424rkeley.edu/~afelt/felt_usenixsec2011.pdf</a></p>
425
426<h3>Creating Permissions</h3>
427
428<p>Generally, you should strive to create as few permissions as possible while
429satisfying your security requirements. Creating a new permission is relatively
430uncommon for most applications, since <a
Scott Maincd1b08e2011-12-27 16:22:27 -0800431href="{@docRoot}reference/android/Manifest.permission.html">system-defined
432permissions</a> cover many situations. Where appropriate,
Adrian Ludwig24359402011-11-07 09:24:23 -0800433perform access checks using existing permissions.</p>
434
435<p>If you must create a new permission, consider whether you can accomplish
436your task with a Signature permission. Signature permissions are transparent
437to the user and only allow access by applications signed by the same developer
438as application performing the permission check. If you create a Dangerous
439permission, then the user needs to decide whether to install the application.
440This can be confusing for other developers, as well as for users.</p>
441
442<p>If you create a Dangerous permission, there are a number of complexities
443that you need to consider.
444<ul>
445<li>The permission must have a string that concisely expresses to a user the
446security decision they will be required to make.</li>
447<li>The permission string must be localized to many different languages.</li>
448<li>Uses may choose not to install an application because a permission is
449confusing or perceived as risky.</li>
450<li>Applications may request the permission when the creator of the permission
451has not been installed.</li>
452</ul></p>
453
454<p>Each of these poses a significant non-technical challenge for an application
455developer, which is why we discourage the use of Dangerous permission.</p>
456
457<a name="Networking"></a>
458<h2>Using Networking</h2>
459
460<h3>Using IP Networking</h3>
461
462<p>Networking on Android is not significantly different from Linux
463environments. The key consideration is making sure that appropriate protocols
464are used for sensitive data, such as <a
465href="{@docRoot}reference/javax/net/ssl/HttpsURLConnection.html">HTTPS</a> for
466web traffic. We prefer use of HTTPS over HTTP anywhere that HTTPS is
467supported on the server, since mobile devices frequently connect on networks
468that are not secured, such as public WiFi hotspots.</p>
469
470<p>Authenticated, encrypted socket-level communication can be easily
471implemented using the <code><a
472href="{@docRoot}reference/javax/net/ssl/SSLSocket.html">SSLSocket</a></code>
473class. Given the frequency with which Android devices connect to unsecured
474wireless networks using WiFi, the use of secure networking is strongly
475encouraged for all applications.</p>
476
477<p>We have seen some applications use <a
478href="http://en.wikipedia.org/wiki/Localhost">localhost</a> network ports for
479handling sensitive IPC. We discourage this approach since these interfaces are
480accessible by other applications on the device. Instead, use an Android IPC
481mechanism where authentication is possible such as a Service and Binder. (Even
482worse than using loopback is to bind to INADDR_ANY since then your application
483may receive requests from anywhere. We’ve seen that, too.)</p>
484
485<p>Also, one common issue that warrants repeating is to make sure that you do
486not trust data downloaded from HTTP or other insecure protocols. This includes
487validation of input in <code><a
488href="{@docRoot}reference/android/webkit/WebView.html">WebView</a></code> and
489any responses to intents issued against HTTP.</p>
490
491<h3>Using Telephony Networking</h3>
492
493<p>SMS is the telephony protocol most frequently used by Android developers.
494Developers should keep in mind that this protocol was primarily designed for
495user-to-user communication and is not well-suited for some application
496purposes. Due to the limitations of SMS, we strongly recommend the use of <a
497href="http://code.google.com/android/c2dm/">C2DM</a> and IP networking for
498sending data messages to devices.</p>
499
500<p>Many developers do not realize that SMS is not encrypted or strongly
501authenticated on the network or on the device. In particular, any SMS receiver
502should expect that a malicious user may have sent the SMS to your application
503-- do not rely on unauthenticated SMS data to perform sensitive commands.
504Also, you should be aware that SMS may be subject to spoofing and/or
505interception on the network. On the Android-powered device itself, SMS
506messages are transmitted as Broadcast intents, so they may be read or captured
507by other applications that have the READ_SMS permission.</p>
508
509<a name="DynamicCode"></a>
510<h2>Dynamically Loading Code</h2>
511
512<p>We strongly discourage loading code from outside of the application APK.
513Doing so significantly increases the likelihood of application compromise due
514to code injection or code tampering. It also adds complexity around version
515management and application testing. Finally, it can make it impossible to
516verify the behavior of an application, so it may be prohibited in some
517environments.</p>
518
519<p>If your application does dynamically load code, the most important thing to
520keep in mind about dynamically loaded code is that it runs with the same
521security permissions as the application APK. The user made a decision to
522install your application based on your identity, and they are expecting that
523you provide any code run within the application, including code that is
524dynamically loaded.</p>
525
526<p>The major security risk associated with dynamically loading code is that the
527code needs to come from a verifiable source. If the modules are included
528directly within your APK, then they cannot be modified by other applications.
529This is true whether the code is a native library or a class being loaded using
530<a href="{@docRoot}reference/dalvik/system/DexClassLoader.html">
531<code>DexClassLoader</code></a>. We have seen many instances of applications
532attempting to load code from insecure locations, such as downloaded from the
533network over unencrypted protocols or from world writable locations such as
534external storage. These locations could allow someone on the network to modify
535the content in transit, or another application on a users device to modify the
536content, respectively.</p>
537
538
539<h3>Using WebView</h3>
540
541<p>Since WebView consumes web content that can include HTML and JavaScript,
542improper use can introduce common web security issues such as <a
543href="http://en.wikipedia.org/wiki/Cross_site_scripting">cross-site-scripting</a
544> (JavaScript injection). Android includes a number of mechanisms to reduce
545the scope of these potential issues by limiting the capability of WebView to
546the minimum functionality required by your application.</p>
547
548<p>If your application does not directly use JavaScript within a <code><a
549href="{@docRoot}reference/android/webkit/WebView.html">WebView</a></code>, do
550not call
Adrian Ludwiga15562f2011-12-15 15:37:33 -0800551<a href="{@docRoot}reference/android/webkit/WebSettings.html#setJavaScriptEnabled(boolean)">
Adrian Ludwig24359402011-11-07 09:24:23 -0800552<code>setJavaScriptEnabled()</code></a>. We have seen this method invoked
553in sample code that might be repurposed in production application -- so
554remove it if necessary. By default, <code><a
555href="{@docRoot}reference/android/webkit/WebView.html">WebView</a></code> does
556not execute JavaScript so cross-site-scripting is not possible.</p>
557
558<p>Use <code><a
Scott Maincd1b08e2011-12-27 16:22:27 -0800559href="{@docRoot}reference/android/webkit/WebView.html#addJavascriptInterface(java.lang.Object,%20java.lang.String)">addJavaScriptInterface()</a></code> with
Adrian Ludwig24359402011-11-07 09:24:23 -0800560particular care because it allows JavaScript to invoke operations that are
561normally reserved for Android applications. Only expose <code><a
Scott Maincd1b08e2011-12-27 16:22:27 -0800562href="{@docRoot}reference/android/webkit/WebView.html#addJavascriptInterface(java.lang.Object,%20java.lang.String)">addJavaScriptInterface()</a></code> to
Adrian Ludwig24359402011-11-07 09:24:23 -0800563sources from which all input is trustworthy. If untrusted input is allowed,
564untrusted JavaScript may be able to invoke Android methods. In general, we
565recommend only exposing <code><a
Scott Maincd1b08e2011-12-27 16:22:27 -0800566href="{@docRoot}reference/android/webkit/WebView.html#addJavascriptInterface(java.lang.Object,%20java.lang.String)">addJavaScriptInterface()</a></code> to
Adrian Ludwig24359402011-11-07 09:24:23 -0800567JavaScript that is contained within your application APK.</p>
568
569<p>Do not trust information downloaded over HTTP, use HTTPS instead. Even if
570you are connecting only to a single website that you trust or control, HTTP is
571subject to <a
572href="http://en.wikipedia.org/wiki/Man-in-the-middle_attack">MiTM</a> attacks
573and interception of data. Sensitive capabilities using <code><a
Scott Maincd1b08e2011-12-27 16:22:27 -0800574href="{@docRoot}reference/android/webkit/WebView.html#addJavascriptInterface(java.lang.Object,%20java.lang.String)">addJavaScriptInterface()</a></code> should
Adrian Ludwig24359402011-11-07 09:24:23 -0800575not ever be exposed to unverified script downloaded over HTTP. Note that even
576with the use of HTTPS,
577<code><a
Scott Maincd1b08e2011-12-27 16:22:27 -0800578href="{@docRoot}reference/android/webkit/WebView.html#addJavascriptInterface(java.lang.Object,%20java.lang.String)">addJavaScriptInterface()</a></code>
Adrian Ludwig24359402011-11-07 09:24:23 -0800579increases the attack surface of your application to include the server
580infrastructure and all CAs trusted by the Android-powered device.</p>
581
582<p>If your application accesses sensitive data with a <code><a
583href="{@docRoot}reference/android/webkit/WebView.html">WebView</a></code>, you
584may want to use the <code><a
585href="{@docRoot}reference/android/webkit/WebView.html#clearCache(boolean)">
586clearCache()</a></code> method to delete any files stored locally. Server side
587headers like no-cache can also be used to indicate that an application should
588not cache particular content.</p>
589
590<a name="Input"></a>
591<h2>Performing Input Validation</h2>
592
593<p>Insufficient input validation is one of the most common security problems
594affecting applications, regardless of what platform they run on. Android does
595have platform-level countermeasures that reduce the exposure of applications to
596input validation issues, you should use those features where possible. Also
597note that selection of type-safe languages tends to reduce the likelihood of
598input validation issues. We strongly recommend building your applications with
599the Android SDK.</p>
600
601<p>If you are using native code, then any data read from files, received over
602the network, or received from an IPC has the potential to introduce a security
603issue. The most common problems are <a
604href="http://en.wikipedia.org/wiki/Buffer_overflow">buffer overflows</a>, <a
605href="http://en.wikipedia.org/wiki/Double_free#Use_after_free">use after
606free</a>, and <a
607href="http://en.wikipedia.org/wiki/Off-by-one_error">off-by-one errors</a>.
608Android provides a number of technologies like ASLR and DEP that reduce the
609exploitability of these errors, but they do not solve the underlying problem.
610These can be prevented by careful handling of pointers and managing of
611buffers.</p>
612
613<p>Dynamic, string based languages such as JavaScript and SQL are also subject
614to input validation problems due to escape characters and <a
615href="http://en.wikipedia.org/wiki/Code_injection">script injection</a>.</p>
616
617<p>If you are using data within queries that are submitted to SQL Database or a
618Content Provider, SQL Injection may be an issue. The best defense is to use
619parameterized queries, as is discussed in the ContentProviders section.
620Limiting permissions to read-only or write-only can also reduce the potential
621for harm related to SQL Injection.</p>
622
623<p>If you are using <code><a
624href="{@docRoot}reference/android/webkit/WebView.html">WebView</a></code>, then
625you must consider the possibility of XSS. If your application does not
626directly use JavaScript within a <code><a
627href="{@docRoot}reference/android/webkit/WebView.html">WebView</a></code>, do
628not call setJavaScriptEnabled() and XSS is no longer possible. If you must
629enable JavaScript then the WebView section provides other security best
630practices.</p>
631
632<p>If you cannot use the security features above, we strongly recommend the use
633of well-structured data formats and verifying that the data conforms to the
634expected format. While blacklisting of characters or character-replacement can
635be an effective strategy, these techniques are error-prone in practice and
636should be avoided when possible.</p>
637
638<a name="UserData"></a>
639<h2>Handling User Data</h2>
640
641<p>In general, the best approach is to minimize use of APIs that access
642sensitive or personal user data. If you have access to data and can avoid
643storing or transmitting the information, do not store or transmit the data.
644Finally, consider if there is a way that your application logic can be
645implemented using a hash or non-reversible form of the data. For example, your
646application might use the hash of an an email address as a primary key, to
647avoid transmitting or storing the email address. This reduces the chances of
648inadvertently exposing data, and it also reduces the chance of attackers
649attempting to exploit your application.</p>
650
651<p>If your application accesses personal information such as passwords or
652usernames, keep in mind that some jurisdictions may require you to provide a
653privacy policy explaining your use and storage of that data. So following the
654security best practice of minimizing access to user data may also simplify
655compliance.</p>
656
657<p>You should also consider whether your application might be inadvertently
658exposing personal information to other parties such as third-party components
659for advertising or third-party services used by your application. If you don't
660know why a component or service requires a personal information, don’t
661provide it. In general, reducing the access to personal information by your
662application will reduce the potential for problems in this area.</p>
663
664<p>If access to sensitive data is required, evaluate whether that information
665must be transmitted to a server, or whether the operation can be performed on
666the client. Consider running any code using sensitive data on the client to
667avoid transmitting user data.</p>
668
669<p>Also, make sure that you do not inadvertently expose user data to other
670application on the device through overly permissive IPC, world writable files,
671or network sockets. This is a special case of permission redelegation,
672discussed in the Requesting Permissions section.</p>
673
674<p>If a GUID is required, create a large, unique number and store it. Do not
675use phone identifiers such as the phone number or IMEI which may be associated
676with personal information. This topic is discussed in more detail in the <a
Scott Maincd1b08e2011-12-27 16:22:27 -0800677href="http://android-developers.blogspot.com/2011/03/identifying-app-installations.html">Android Developer Blog</a>.</p>
Adrian Ludwig24359402011-11-07 09:24:23 -0800678
Adrian Ludwiga15562f2011-12-15 15:37:33 -0800679<p>Application developers should be careful writing to on-device logs.
680In Android, logs are a shared resource, and are available
681to an application with the
682<a href="{@docRoot}reference/android/Manifest.permission.html#READ_LOGS">
683<code>READ_LOGS</code></a> permission. Even though the phone log data
684is temporary and erased on reboot, inappropriate logging of user information
685could inadvertently leak user data to other applications.</p>
686
687
Adrian Ludwig24359402011-11-07 09:24:23 -0800688<h3>Handling Credentials</h3>
689
690<p>In general, we recommend minimizing the frequency of asking for user
691credentials -- to make phishing attacks more conspicuous, and less likely to be
692successful. Instead use an authorization token and refresh it.</p>
693
694<p>Where possible, username and password should not be stored on the device.
695Instead, perform initial authentication using the username and password
696supplied by the user, and then use a short-lived, service-specific
697authorization token.</p>
698
699<p>Services that will be accessible to multiple applications should be accessed
700using <code>
701<a href="{@docRoot}reference/android/accounts/AccountManager.html">
702AccountManager</a></code>. If possible, use the <code><a
703href="{@docRoot}reference/android/accounts/AccountManager.html">
704AccountManager</a></code> class to invoke a cloud-based service and do not store
705passwords on the device.</p>
706
707<p>After using <code><a
708href="{@docRoot}reference/android/accounts/AccountManager.html">
709AccountManager</a></code> to retrieve an Account, check the <code><a
710href="{@docRoot}reference/android/accounts/Account.html#CREATOR">CREATOR</a>
711</code> before passing in any credentials, so that you do not inadvertently pass
712credentials to the wrong application.</p>
713
714<p>If credentials are to be used only by applications that you create, then you
715can verify the application which accesses the <code><a
716href="{@docRoot}reference/android/accounts/AccountManager.html">
Scott Maincd1b08e2011-12-27 16:22:27 -0800717AccountManager</a></code> using <code><a
718href="{@docRoot}reference/android/content/pm/PackageManager.html#checkSignatures(java.lang.String,%20java.lang.String)">checkSignature()</a></code>.
Adrian Ludwig24359402011-11-07 09:24:23 -0800719Alternatively, if only one application will use the credential, you might use a
720<code><a
721href={@docRoot}reference/java/security/KeyStore.html">KeyStore</a></code> for
722storage.</p>
723
724<a name="Crypto"></a>
725<h2>Using Cryptography</h2>
726
727<p>In addition to providing data isolation, supporting full-filesystem
728encryption, and providing secure communications channels Android provides a
729wide array of algorithms for protecting data using cryptography.</p>
730
731<p>In general, try to use the highest level of pre-existing framework
732implementation that can support your use case. If you need to securely
733retrieve a file from a known location, a simple HTTPS URI may be adequate and
734require no knowledge of cryptography on your part. If you need a secure
735tunnel, consider using
736<a href="{@docRoot}reference/javax/net/ssl/HttpsURLConnection.html">
737<code>HttpsURLConnection</code></a> or <code><a
738href="{@docRoot}reference/javax/net/ssl/SSLSocket.html">SSLSocket</a></code>,
739rather than writing your own protocol.</p>
740
741<p>If you do find yourself needing to implement your own protocol, we strongly
742recommend that you not implement your own cryptographic algorithms. Use
743existing cryptographic algorithms such as those in the implementation of AES or
744RSA provided in the <code><a
745href="{@docRoot}reference/javax/crypto/Cipher.html">Cipher</a></code> class.</p>
746
747<p>Use a secure random number generator (
Scott Maincd1b08e2011-12-27 16:22:27 -0800748<a href="{@docRoot}reference/java/security/SecureRandom.html">
Adrian Ludwig24359402011-11-07 09:24:23 -0800749<code>SecureRandom</code></a>) to initialize any cryptographic keys (<a
Scott Maincd1b08e2011-12-27 16:22:27 -0800750href="{@docRoot}reference/javax/crypto/KeyGenerator.html">
Adrian Ludwig24359402011-11-07 09:24:23 -0800751<code>KeyGenerator</code></a>). Use of a key that is not generated with a secure random
752number generator significantly weakens the strength of the algorithm, and may
753allow offline attacks.</p>
754
755<p>If you need to store a key for repeated use, use a mechanism like <code><a
Scott Maincd1b08e2011-12-27 16:22:27 -0800756href="{@docRoot}reference/java/security/KeyStore.html">KeyStore</a></code> that
Adrian Ludwig24359402011-11-07 09:24:23 -0800757provides a mechanism for long term storage and retrieval of cryptographic
758keys.</p>
759
760<h2>Conclusion</h2>
761
762<p>Android provides developers with the ability to design applications with a
763broad range of security requirements. These best practices will help you make
764sure that your application takes advantage of the security benefits provided by
765the platform.</p>
766
767<p>You can receive more information on these topics and discuss security best
768practices with other developers in the <a
769href="http://groups.google.com/group/android-security-discuss">Android Security
770Discuss</a> Google Group</p>