• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1page.title=Security Tips
2page.article=true
3@jd:body
4
5<div id="tb-wrapper">
6<div id="tb">
7<h2>In this document</h2>
8<ol class="nolist">
9  <li><a href="#StoringData">Storing data</a></li>
10  <li><a href="#Permissions">Using permissions</a></li>
11  <li><a href="#Networking">Using networking</a></li>
12  <li><a href="#InputValidation">Performing input validation</a></li>
13  <li><a href="#UserData">Handling user data</a></li>
14  <li><a href="#WebView">Using WebView</a></li>
15  <li><a href="#Crypto">Using cryptography</a></li>
16  <li><a href="#IPC">Using interprocess communication</a></li>
17  <li><a href="#DynamicCode">Dynamically loading code</a></li>
18  <li><a href="#Dalvik">Security in a virtual machine</a></li>
19  <li><a href="#Native">Security in native code</a></li>
20</ol>
21<h2>See also</h2>
22<ul>
23<li><a href="http://source.android.com/tech/security/index.html">Android
24  Security Overview</a></li>
25<li><a href="{@docRoot}guide/topics/security/permissions.html">Permissions</a></li>
26</ul>
27</div></div>
28
29
30<p>Android has built-in security features that significantly reduce the frequency and impact of
31application security issues. The system is designed so that you can typically build your apps with
32the default system and file permissions and avoid difficult decisions about security.</p>
33
34<p>The following core security features help you build secure apps:
35<ul>
36<li>The Android Application Sandbox, which isolates your app data and code execution
37from other apps.</li>
38<li>An application framework with robust implementations of common
39security functionality such as cryptography, permissions, and secure
40<acronym title="Interprocess Communication">IPC</acronym>.</li>
41<li>Technologies like ASLR, NX, ProPolice, safe_iop, OpenBSD dlmalloc, OpenBSD
42calloc, and Linux mmap_min_addr to mitigate risks associated with common memory
43management errors.</li>
44<li>An encrypted file system that can be enabled to protect data on lost or
45stolen devices.</li>
46<li>User-granted permissions to restrict access to system features and user data.</li>
47<li>Application-defined permissions to control application data on a per-app basis.</li>
48</ul>
49
50<p>It is important that you be familiar with the Android
51security best practices in this document. Following these practices as general coding habits
52 reduces the likelihood of inadvertently introducing security issues that
53adversely affect your users.</p>
54
55
56
57<h2 id="StoringData">Storing data</h2>
58
59<p>The most common security concern for an application on Android is whether the data
60that you save on the device is accessible to other apps. There are three fundamental
61ways to save data on the device:</p>
62
63<ul>
64<li>Internal storage.</li>
65<li>External storage.</li>
66<li>Content providers.</li>
67</ul>
68
69The following paragraphs describe the security issues associated with each approach.
70
71<h3 id="InternalStorage">Using internal storage</h3>
72
73<p>By default, files that you create on <a
74href="{@docRoot}guide/topics/data/data-storage.html#filesInternal">internal
75storage</a> are accessible only to your app.
76 Android implements this protection, and it's sufficient for most applications.</p>
77
78<p>Generally, avoid the {@link android.content.Context#MODE_WORLD_WRITEABLE} or
79{@link android.content.Context#MODE_WORLD_READABLE} modes for
80<acronym title="Interprocess Communication">IPC</acronym> files because they do not provide
81the ability to limit data access to particular applications, nor do they
82provide any control of data format. If you want to share your data with other
83app processes, instead consider using a
84<a href="{@docRoot}guide/topics/providers/content-providers.html">content provider</a>, which
85offers read and write permissions to other apps and can make
86dynamic permission grants on a case-by-case basis.</p>
87
88<p>To provide additional protection for sensitive data, you can
89 encrypt local files using a key that is not directly accessible to the
90application. For example, you can place a key in a {@link java.security.KeyStore}
91and protect it with a user password that is not stored on the device.  While this
92does not protect data from a root compromise that can monitor the user
93inputting the password,  it can provide protection for a lost device without <a
94href="http://source.android.com/tech/encryption/index.html">file system
95encryption</a>.</p>
96
97
98<h3 id="ExternalStorage">Using external storage</h3>
99
100<p>Files created on <a
101href="{@docRoot}guide/topics/data/data-storage.html#filesExternal">external
102storage</a>, such as SD cards, are globally readable and writable. Because
103external storage can be removed by the user and also modified by any
104application, don't store sensitive information using
105external storage.</p>
106
107<p>You should <a href="#InputValidation">Perform input validation</a> when handling
108data from external storage as you would with data from any untrusted source.
109You should not store executables or
110class files on external storage prior to dynamic loading.  If your app
111does retrieve executable files from external storage, the files should be signed and
112cryptographically verified prior to dynamic loading.</p>
113
114
115<h3 id="ContentProviders">Using content providers</h3>
116
117<p><a href="{@docRoot}guide/topics/providers/content-providers.html">Content providers</a>
118offer a structured storage mechanism that can be limited
119to your own application or exported to allow access by other applications.
120If you do not intend to provide other
121applications with access to your {@link android.content.ContentProvider}, mark them as <code><a
122href="{@docRoot}guide/topics/manifest/provider-element.html#exported">
123android:exported=false</a></code> in the application manifest. Otherwise, set the <code><a
124href="{@docRoot}guide/topics/manifest/provider-element.html#exported">android:exported</a></code>
125attribute to {@code true} to allow other apps to access the stored data.
126</p>
127
128<p>When creating a {@link android.content.ContentProvider}
129that is exported for use by other applications, you can specify a single
130<a href="{@docRoot}guide/topics/manifest/provider-element.html#prmsn">permission
131</a> for reading and writing, or you can specify distinct permissions for reading and writing.
132You should limit your permissions to those
133required to accomplish the task at hand. Keep in mind that it’s usually
134easier to add permissions later to expose new functionality than it is to take
135them away and impact existing users.</p>
136
137<p>If you are using a content provider
138for sharing data between only your own apps, it is preferable to use the
139<a href="{@docRoot}guide/topics/manifest/permission-element.html#plevel">{@code
140android:protectionLevel}</a> attribute set to {@code signature} protection.
141Signature permissions do not require user confirmation,
142so they provide a better user experience and more controlled access to the
143content provider data when the apps accessing the data are
144<a href="{@docRoot}tools/publishing/app-signing.html">signed</a> with
145the same key.</p>
146
147<p>Content providers can also provide more granular access by declaring the <a
148href="{@docRoot}guide/topics/manifest/provider-element.html#gprmsn">{@code
149android:grantUriPermissions}</a> attribute and using the {@link
150android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION} and {@link
151android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION} flags in the
152{@link android.content.Intent} object
153that activates the component.  The scope of these permissions can be further
154limited by the <code><a
155href="{@docRoot}guide/topics/manifest/grant-uri-permission-element.html">
156&lt;grant-uri-permission&gt;</a></code> element.</p>
157
158<p>When accessing a content provider, use parameterized query methods such as
159{@link android.content.ContentProvider#query(Uri,String[],String,String[],String) query()},
160{@link android.content.ContentProvider#update(Uri,ContentValues,String,String[]) update()}, and
161{@link android.content.ContentProvider#delete(Uri,String,String[]) delete()} to avoid
162potential SQL injection from untrusted sources. Note that using parameterized methods is not
163sufficient if the <code>selection</code> argument is built by concatenating user data
164prior to submitting it to the method.</p>
165
166<p>Don't have a false sense of security about the write permission.
167 The write permission allows SQL statements that make it possible for some
168data to be confirmed using creative <code>WHERE</code> clauses and parsing the
169results. For example, an attacker might probe for the presence of a specific phone
170number in a call log by modifying a row only if that phone number already
171exists. If the content provider data has predictable structure, the write
172permission may be equivalent to providing both reading and writing.</p>
173
174
175
176
177
178
179
180<h2 id="Permissions">Using permissions</h2>
181
182<p>Because Android sandboxes applications from each other, applications must explicitly
183share resources and data. They do this by declaring the permissions they need for additional
184capabilities not provided by the basic sandbox, including access to device features such as
185the camera.</p>
186
187
188<h3 id="RequestingPermissions">Requesting permissions</h3>
189
190<p>You should minimize the number of permissions that your app requests.
191Restricting access to sensitive permissions reduces the risk of
192inadvertently misusing those permissions, improves user adoption, and makes
193your app less vulnerable for attackers. Generally,
194if a permission is not required for your app to function, don't request it.</p>
195
196<p>If it's possible to design your application in a way that does not require
197any permissions, that is preferable.  For example, rather than requesting access
198to device information to create a unique identifier, create a <a
199href="{@docRoot}reference/java/util/UUID.html">GUID</a> for your application
200(see the section about <a href="#UserData">Handling user data</a>). Or, rather than
201using external storage (which requires permission), store data
202on the internal storage.</p>
203
204<p>In addition to requesting permissions, your application can use the <a
205href="{@docRoot}guide/topics/manifest/permission-element.html">{@code &lt;permission&gt;}</a>
206 element to protect IPC that is security sensitive and is exposed to other
207applications, such as a {@link android.content.ContentProvider}.
208In general, we recommend using access controls
209other than user confirmed permissions where possible because permissions can
210be confusing for users. For example, consider using the <a
211href="{@docRoot}guide/topics/manifest/permission-element.html#plevel">signature
212protection level</a> on permissions for IPC communication between applications
213provided by a single developer.</p>
214
215<p>Do not leak permission-protected data. This occurs when your app exposes
216data over IPC that is available only because your app has permission to access
217that data. The clients of your app's IPC interface may not have that same
218data-access permission. More details on the frequency and potential effects
219of this issue appear in the research paper <a
220href="https://www.usenix.org/legacy/event/sec11/tech/full_papers/Felt.pdf" class="external-link">
221Permission Re-Delegation: Attacks and Defenses
222</a>, published at USENIX.
223
224
225
226<h3 id="CreatingPermissions">Creating permissions</h3>
227
228<p>Generally, you should strive to define as few permissions as possible while
229satisfying your security requirements.  Creating a new permission is relatively
230uncommon for most applications, because the <a
231href="{@docRoot}reference/android/Manifest.permission.html">system-defined
232permissions</a> cover many situations.  Where appropriate,
233perform access checks using existing permissions.</p>
234
235<p>If you must create a new permission, consider whether you can accomplish
236your task with a <a
237href="{@docRoot}guide/topics/manifest/permission-element.html#plevel">signature
238protection level</a>.  Signature permissions are transparent
239to the user and allow access only by applications signed by the same developer
240as the application performing the permission check.</p>
241
242<p>If you create a permission with the <a
243href="{@docRoot}guide/topics/manifest/permission-element.html#plevel">dangerous
244protection level</a>, there are a number of complexities
245that you need to consider:
246<ul>
247<li>The permission must have a string that concisely expresses to a user the
248security decision they are required to make.</li>
249<li>The permission string must be localized to many different languages.</li>
250<li>Users may choose not to install an application because a permission is
251confusing or perceived as risky.</li>
252<li>Applications may request the permission when the creator of the permission
253has not been installed.</li>
254</ul>
255
256<p>Each of these poses a significant nontechnical challenge for you as the developer
257while also confusing your users,
258which is why we discourages the use of the <em>dangerous</em> permission level.</p>
259
260
261
262
263
264<h2 id="Networking">Using networking</h2>
265
266<p>Network transactions are inherently risky for security, because they involve transmitting
267data that is potentially private to the user. People are increasingly aware of the privacy
268concerns of a mobile device, especially when the device performs network transactions,
269so it's very important that your app implement all best practices toward keeping the user's
270data secure at all times.</p>
271
272<h3 id="IPNetworking">Using IP networking</h3>
273
274<p>Networking on Android is not significantly different from other Linux
275environments.  The key consideration is making sure that appropriate protocols
276are used for sensitive data, such as {@link javax.net.ssl.HttpsURLConnection} for
277secure web traffic. You should use HTTPS over HTTP anywhere that HTTPS is
278supported on the server, because mobile devices frequently connect on networks
279that are not secured, such as public Wi-Fi hotspots.</p>
280
281<p>Authenticated, encrypted socket-level communication can be easily
282implemented using the {@link javax.net.ssl.SSLSocket}
283class.  Given the frequency with which Android devices connect to unsecured
284wireless networks using Wi-Fi, the use of secure networking is strongly
285encouraged for all applications that communicate over the network.</p>
286
287<p>Some applications use <a
288href="http://en.wikipedia.org/wiki/Localhost" class="external-link">localhost</a> network ports for
289handling sensitive IPC.  You should not use this approach because these interfaces are
290accessible by other applications on the device. Instead, use an Android IPC
291mechanism where authentication is possible, such as with a {@link android.app.Service}.
292Binding to INADDR_ANY is worse than using loopback because then your application
293may receive requests from anywhere.</p>
294
295<p>Make sure that you don't
296 trust data downloaded from HTTP or other insecure protocols.  This includes
297validation of input in {@link android.webkit.WebView} and
298any responses to intents issued against HTTP.</p>
299
300
301<h3>Using telephony networking</h3>
302
303<p>The <acronym title="Short Message Service">SMS</acronym> protocol was primarily designed for
304user-to-user communication and is not well-suited for apps that want to transfer data.
305Due to the limitations of SMS, you should use <a
306href="{@docRoot}google/gcm/index.html">Google Cloud Messaging</a> (GCM)
307and IP networking for sending data messages from a web server to your app on a user device.</p>
308
309<p>Beware that SMS is neither encrypted nor strongly
310authenticated on either the network or the device. In particular, any SMS receiver
311should expect that a malicious user may have sent the SMS to your application. Don't
312 rely on unauthenticated SMS data to perform sensitive commands.
313Also, you should be aware that SMS may be subject to spoofing and/or
314interception on the network.  On the Android-powered device itself, SMS
315messages are transmitted as broadcast intents, so they may be read or captured
316by other applications that have the {@link android.Manifest.permission#READ_SMS}
317permission.</p>
318
319
320
321
322
323<h2 id="InputValidation">Performing input validation</h2>
324
325<p>Insufficient input validation is one of the most common security problems
326affecting applications, regardless of what platform they run on. Android
327has platform-level countermeasures that reduce the exposure of applications to
328input validation issues, and you should use those features where possible. Also
329note that the selection of type-safe languages tends to reduce the likelihood of
330input validation issues.</p>
331
332<p>If you are using native code, any data read from files, received over
333the network, or received from an IPC has the potential to introduce a security
334issue.  The most common problems are <a
335href="http://en.wikipedia.org/wiki/Buffer_overflow" class="external-link">buffer overflows</a>, <a
336href="http://en.wikipedia.org/wiki/Double_free#Use_after_free" class="external-link">use after
337free</a>, and <a
338href="http://en.wikipedia.org/wiki/Off-by-one_error" class="external-link">off-by-one errors</a>.
339Android provides a number of technologies like <acronym
340title="Address Space Layout Randomization">ASLR</acronym> and <acronym
341title="Data Execution Prevention">DEP</acronym> that reduce the
342exploitability of these errors, but they don't solve the underlying problem.
343You can prevent these vulnerabilities by carefully handling pointers and managing
344buffers.</p>
345
346<p>Dynamic, string-based languages such as JavaScript and SQL are also subject
347to input validation problems due to escape characters and <a
348href="http://en.wikipedia.org/wiki/Code_injection" class="external-link">script injection</a>.</p>
349
350<p>If you are using data within queries that are submitted to an SQL database or a
351content provider, SQL injection may be an issue.  The best defense is to use
352parameterized queries, as is discussed in the above section about <a
353href="#ContentProviders">content providers</a>.
354Limiting permissions to read-only or write-only can also reduce the potential
355for harm related to SQL injection.</p>
356
357<p>If you can't use the security features above, you should make sure to use
358well-structured data formats and verify that the data conforms to the
359expected format. While blacklisting of characters or character-replacement can
360be an effective strategy, these techniques are error prone in practice and
361should be avoided when possible.</p>
362
363
364
365
366
367<h2 id="UserData">Handling user data</h2>
368
369<p>In general, the best approach for user data security is to minimize the use of APIs that access
370sensitive or personal user data. If you have access to user data and can avoid
371storing or transmitting it, don't store or transmit the data.
372Consider if there is a way that your application logic can be
373implemented using a hash or non-reversible form of the data.  For example, your
374application might use the hash of an email address as a primary key to
375avoid transmitting or storing the email address.  This reduces the chances of
376inadvertently exposing data, and it also reduces the chance of attackers
377attempting to exploit your application.</p>
378
379<p>If your application accesses personal information such as passwords or
380user names, keep in mind that some jurisdictions may require you to provide a
381privacy policy explaining your use and storage of that data. Following the
382security best practice of minimizing access to user data may also simplify
383compliance.</p>
384
385<p>You should also consider whether your application might be inadvertently
386exposing personal information to other parties such as third-party components
387for advertising or third-party services used by your application. If you don't
388know why a component or service requires personal information, don’t
389provide it.  In general, reducing the access to personal information by your
390application reduces the potential for problems in this area.</p>
391
392<p>If your app requires access to sensitive data, evaluate whether you need to
393 transmit it to a server or you can run the operation on
394the client. Consider running any code using sensitive data on the client to
395avoid transmitting user data. Also, make sure that you do not inadvertently expose user
396 data to other
397applications on the device through overly permissive IPC, world-writable files,
398or network sockets. Overly permissive IPC is a special case of leaking permission-protected data,
399discussed in the <a href="#RequestingPermissions">Requesting Permissions</a> section.</p>
400
401<p>If a <acronym title="Globally Unique Identifier">GUID</acronym>
402is required, create a large, unique number and store it.  Don't
403use phone identifiers such as the phone number or IMEI, which may be associated
404with personal information.  This topic is discussed in more detail in the <a
405href="http://android-developers.blogspot.com/2011/03/identifying-app-installations.html"
406>Android Developer Blog</a>.</p>
407
408<p>Be careful when writing to on-device logs.
409In Android, logs are a shared resource and are available
410to an application with the {@link android.Manifest.permission#READ_LOGS} permission.
411Even though the phone log data
412is temporary and erased on reboot, inappropriate logging of user information
413could inadvertently leak user data to other applications.</p>
414
415
416
417
418
419
420<h2 id="WebView">Using WebView</h2>
421
422<p>Because {@link android.webkit.WebView} consumes web content that can include HTML
423 and JavaScript,
424improper use can introduce common web security issues such as <a
425href="http://en.wikipedia.org/wiki/Cross_site_scripting" class="external-link">
426cross-site-scripting</a>
427(JavaScript injection).  Android includes a number of mechanisms to reduce
428the scope of these potential issues by limiting the capability of
429 {@link android.webkit.WebView} to
430the minimum functionality required by your application.</p>
431
432<p>If your application doesn't directly use JavaScript within a {@link android.webkit.WebView},
433 <em>do not</em> call
434 {@link android.webkit.WebSettings#setJavaScriptEnabled setJavaScriptEnabled()}.
435Some sample code uses this method, which you might repurpose in production
436application, so remove that method call if it's not required. By default,
437{@link android.webkit.WebView} does
438not execute JavaScript, so cross-site-scripting is not possible.</p>
439
440<p>Use {@link android.webkit.WebView#addJavascriptInterface
441addJavaScriptInterface()} with
442particular care because it allows JavaScript to invoke operations that are
443normally reserved for Android applications.  If you use it, expose
444{@link android.webkit.WebView#addJavascriptInterface addJavaScriptInterface()} only to
445web pages from which all input is trustworthy.  If untrusted input is allowed,
446untrusted JavaScript may be able to invoke Android methods within your app.  In general, we
447recommend exposing {@link android.webkit.WebView#addJavascriptInterface
448addJavaScriptInterface()} only to JavaScript that is contained within your application APK.</p>
449
450<p>If your application accesses sensitive data with a
451{@link android.webkit.WebView}, you may want to use the
452{@link android.webkit.WebView#clearCache clearCache()} method to delete any files stored
453locally. You can also use server-side
454headers such as <code>no-cache</code> to indicate that an application should
455not cache particular content.</p>
456
457<p>Devices running platforms older than Android 4.4 (API level 19)
458use a version of {@link android.webkit webkit} that has a number of security issues.
459As a workaround, if your app is running on these devices, it
460must confirm that {@link android.webkit.WebView} objects display only trusted
461content. To make sure your app isn’t exposed to
462potential vulnerabilities in SSL, use the updatable security {@link
463java.security.Provider Provider} object as described in <a
464href="{@docRoot}training/articles/security-gms-provider.html">Updating Your
465Security Provider to Protect Against SSL Exploits</a>. If your application must
466render content from the open web, consider providing your own renderer so
467you can keep it up to date with the latest security patches.</p>
468
469
470<h3 id="Credentials">Handling credentials</h3>
471
472<p>To make phishing attacks more conspicuous and less likely to be
473successful, minimize the frequency of asking for user
474credentials. Instead use an authorization token and refresh it.</p>
475
476<p>Where possible, don't store user names and passwords on the device.
477Instead, perform initial authentication using the user name and password
478 supplied by the user, and then use a short-lived, service-specific
479authorization token.</p>
480
481<p>Services that are accessible to multiple applications should be accessed
482using {@link android.accounts.AccountManager}. If possible, use the
483{@link android.accounts.AccountManager} class to invoke a cloud-based service and don't store
484passwords on the device.</p>
485
486<p>After using {@link android.accounts.AccountManager} to retrieve an
487{@link android.accounts.Account}, use {@link android.accounts.Account#CREATOR}
488before passing in any credentials so that you do not inadvertently pass
489credentials to the wrong application.</p>
490
491<p>If credentials are used only by applications that you create, you
492can verify the application that accesses the {@link android.accounts.AccountManager} using
493{@link android.content.pm.PackageManager#checkSignatures checkSignature()}.
494Alternatively, if only one application uses the credential, you might use a
495{@link java.security.KeyStore} for storage.</p>
496
497
498
499
500
501<h2 id="Crypto">Using cryptography</h2>
502
503<p>In addition to providing data isolation, supporting full-filesystem
504encryption, and providing secure communications channels, Android provides a
505wide array of algorithms for protecting data using cryptography.</p>
506
507<p>In general, try to use the highest level of pre-existing framework
508implementation that can  support your use case.  If you need to securely
509retrieve a file from a known location, a simple HTTPS URI may be adequate and
510requires no knowledge of cryptography.  If you need a secure
511tunnel, consider using {@link javax.net.ssl.HttpsURLConnection} or
512{@link javax.net.ssl.SSLSocket} rather than writing your own protocol.</p>
513
514<p>If you do need to implement your own protocol, you should <em>not</em>
515implement your own cryptographic algorithms. Use
516existing cryptographic algorithms such as those in the implementation of AES or
517RSA provided in the {@link javax.crypto.Cipher} class.</p>
518
519<p>Use a secure random number generator, {@link java.security.SecureRandom},
520to initialize any cryptographic keys generated by {@link javax.crypto.KeyGenerator}.
521Use of a key that is not generated with a secure random
522number generator significantly weakens the strength of the algorithm and may
523allow offline attacks.</p>
524
525<p>If you need to store a key for repeated use, use a mechanism, such as
526  {@link java.security.KeyStore}, that
527provides a mechanism for long term storage and retrieval of cryptographic
528keys.</p>
529
530
531
532
533
534<h2 id="IPC">Using interprocess communication</h2>
535
536<p>Some apps attempt to implement IPC using traditional Linux
537techniques such as network sockets and shared files. However, you should instead
538use Android system functionality for IPC such as {@link android.content.Intent},
539{@link android.os.Binder} or {@link android.os.Messenger} with a {@link
540android.app.Service}, and {@link android.content.BroadcastReceiver}.
541The Android IPC mechanisms allow you to verify the identity of
542the application connecting to your IPC and set security policy for each IPC
543mechanism.</p>
544
545<p>Many of the security elements are shared across IPC mechanisms.
546If your IPC mechanism is not intended for use by other applications, set the
547{@code android:exported} attribute to {@code false} in the component's manifest element,
548such as for the <a
549href="{@docRoot}guide/topics/manifest/service-element.html#exported">{@code &lt;service&gt;}</a>
550element.  This is useful for applications that consist of multiple processes
551within the same UID or if you decide late in development that you don't
552actually want to expose functionality as IPC, but you don’t want to rewrite
553the code.</p>
554
555<p>If your IPC is accessible to other applications, you can
556apply a security policy by using the <a
557href="{@docRoot}guide/topics/manifest/permission-element.html">{@code &lt;permission>}</a>
558element. If IPC is between your own separate apps that are signed with the same key,
559it is preferable to use {@code signature} level permission in the <a
560href="{@docRoot}guide/topics/manifest/permission-element.html#plevel">{@code
561android:protectionLevel}</a>.</p>
562
563
564
565
566<h3>Using intents</h3>
567
568<p>For activities and broadcast receivers, intents are the preferred mechanism for
569 asynchronous IPC in Android.
570Depending on your application requirements, you might use {@link
571android.content.Context#sendBroadcast sendBroadcast()}, {@link
572android.content.Context#sendOrderedBroadcast sendOrderedBroadcast()},
573or an explicit intent to a specific application component.</p>
574
575<p class="caution"><strong>Caution:</strong> If you use an intent to bind to a
576 {@link android.app.Service}, ensure that your app is secure by using an
577 <a href="{@docRoot}guide/components/intents-filters.html#Types">explicit</a>
578intent. Using an implicit intent to start a service is a
579security hazard because you can't be certain what service will respond to the intent,
580and the user can't see which service starts. Beginning with Android 5.0 (API level 21),
581 the system
582throws an exception if you call {@link android.content.Context#bindService bindService()}
583with an implicit intent.</p>
584
585<p>Note that ordered broadcasts can be <em>consumed</em> by a recipient, so they
586may not be delivered to all applications.  If you are sending an intent that must be delivered
587to a specific receiver, you must use an explicit intent that declares the receiver
588by name.</p>
589
590<p>Senders of an intent can verify that the recipient has permission
591 by specifying a non-null permission with the method call.  Only applications with that
592permission receive the intent. If data within a broadcast intent may be
593sensitive, you should consider applying a permission to make sure that
594malicious applications can't register to receive those messages without
595appropriate permissions. In those circumstances, you may also consider
596invoking the receiver directly, rather than raising a broadcast.</p>
597
598<p class="note"><strong>Note:</strong> Intent filters should not be considered
599a security feature. Components
600can be invoked with explicit intents and may not have data that would conform to the intent
601filter. To
602confirm that it is properly formatted for the invoked receiver, service, or
603activity, perform input validation within your intent receiver.</p>
604
605
606
607
608<h3 id="Services">Using services</h3>
609
610<p>A {@link android.app.Service} is often used to supply functionality for other applications to
611use. Each service class must have a corresponding <a
612href="{@docRoot}guide/topics/manifest/service-element.html">{@code <service>}</a>
613 declaration in its
614manifest file.</p>
615
616<p>By default, services are not exported and cannot be invoked by any other
617application. However, if you add any intent filters to the service declaration, it is exported
618by default. It's best if you explicitly declare the <a
619href="{@docRoot}guide/topics/manifest/service-element.html#exported">{@code
620android:exported}</a> attribute to be sure it behaves as you'd like.
621Services can also be protected using the <a
622href="{@docRoot}guide/topics/manifest/service-element.html#prmsn">{@code android:permission}</a>
623attribute. By doing so, other applications need to declare
624a corresponding <code><a
625href="{@docRoot}guide/topics/manifest/uses-permission-element.html">&lt;uses-permission&gt;</a>
626</code> element in their own manifest to be
627able to start, stop, or bind to the service.</p>
628
629<p class="note"><strong>Note:</strong> If your app targets Android 5.0 (API level 21) or later,
630 you should use the {@link android.app.job.JobScheduler} to execute background
631 services. For more information about {@link android.app.job.JobScheduler}, see its
632 {@link android.app.job.JobScheduler API-reference documentation}.</p>
633
634<p>A service can protect individual IPC calls into it with permissions, by
635calling {@link android.content.Context#checkCallingPermission
636checkCallingPermission()} before executing
637the implementation of that call. You should use the
638declarative permissions in the manifest, since those are less prone to
639oversight.</p>
640
641
642
643<h3>Using binder and messenger interfaces</h3>
644
645<p>Using {@link android.os.Binder} or {@link android.os.Messenger} is the
646preferred mechanism for RPC-style IPC in Android. They provide a well-defined
647interface that enables mutual authentication of the endpoints, if required.</p>
648
649<p>You should design your app interfaces in a manner that does not require
650interface-specific permission checks. {@link android.os.Binder} and
651{@link android.os.Messenger} objects are not declared within the
652application manifest, and therefore you cannot apply declarative permissions
653directly to them.  They generally inherit permissions declared in the
654application manifest for the {@link android.app.Service} or {@link
655android.app.Activity} within which they are
656implemented.  If you are creating an interface that requires authentication
657and/or access controls, you must explicitly add those controls
658 as code in the {@link android.os.Binder} or {@link android.os.Messenger}
659interface.</p>
660
661<p>If you are providing an interface that does require access controls, use {@link
662android.content.Context#checkCallingPermission checkCallingPermission()}
663to verify whether the
664caller has a required permission. This is especially important
665before accessing a service on behalf of the caller, as the identify of your
666application is passed to other interfaces.  If you are invoking an interface provided
667by a {@link android.app.Service}, the {@link
668android.content.Context#bindService bindService()}
669 invocation may fail if you do not have permission to access the given service.
670 If calling an interface provided locally by your own application, it may be
671useful to use the {@link android.os.Binder#clearCallingIdentity clearCallingIdentity()}
672to satisfy internal security checks.</p>
673
674<p>For more information about performing IPC with a service, see
675<a href="{@docRoot}guide/components/bound-services.html">Bound Services</a>.</p>
676
677
678
679<h3 id="BroadcastReceivers">Using broadcast receivers</h3>
680
681<p>A {@link android.content.BroadcastReceiver} handles asynchronous requests initiated by
682an {@link android.content.Intent}.</p>
683
684<p>By default, receivers are exported and can be invoked by any other
685application. If your {@link android.content.BroadcastReceiver}
686is intended for use by other applications, you
687may want to apply security permissions to receivers using the <code><a
688href="{@docRoot}guide/topics/manifest/receiver-element.html">
689&lt;receiver&gt;</a></code> element within the application manifest.  This
690prevents applications without appropriate permissions from sending an intent to
691the {@link android.content.BroadcastReceiver}.</p>
692
693
694
695
696
697
698
699
700<h2 id="DynamicCode">Dynamically loading code</h2>
701
702<p>We strongly discourage loading code from outside of your application APK.
703Doing so significantly increases the likelihood of application compromise due
704to code injection or code tampering. It also adds complexity around version
705management and application testing. It can also make it impossible to
706verify the behavior of an application, so it may be prohibited in some
707environments.</p>
708
709<p>If your application does dynamically load code, the most important thing to
710keep in mind about dynamically-loaded code is that it runs with the same
711security permissions as the application APK.  The user makes a decision to
712install your application based on your identity, and the user expects that
713you provide any code run within the application, including code that is
714dynamically loaded.</p>
715
716<p>The major security risk associated with dynamically loading code is that the
717code needs to come from a verifiable source. If the modules are included
718directly within your APK, they cannot be modified by other applications.
719This is true whether the code is a native library or a class being loaded using
720{@link dalvik.system.DexClassLoader}.  Many applications
721attempt to load code from insecure locations, such as downloaded from the
722network over unencrypted protocols or from world-writable locations such as
723external storage. These locations could allow someone on the network to modify
724the content in transit or another application on a user's device to modify the
725content on the device.</p>
726
727
728
729
730
731<h2 id="Dalvik">Security in a virtual machine</h2>
732
733<p>Dalvik is Android's runtime virtual machine (VM). Dalvik was built specifically for Android,
734but many of the concerns regarding secure code in other virtual machines also apply to Android.
735In general, you shouldn't concern yourself with security issues relating to the virtual machine.
736Your application runs in a secure sandbox environment, so other processes on the system can't
737access your code or private data.</p>
738
739<p>If you're interested in learning more about virtual machine security,
740 familiarize yourself with some
741existing literature on the subject. Two of the more popular resources are:
742<ul>
743<li><a href="http://www.securingjava.com/toc.html" class="external-link">
744Securing Java</a></li>
745<li><a
746href="https://www.owasp.org/index.php/Category:Java#tab=Related_3rd_Party_Projects"
747 class="external-link">
748Related 3rd party Projects</a></li>
749</ul></p>
750
751<p>This document focuses on areas that are Android specific or
752different from other VM environments.  For developers experienced with VM
753programming in other environments, there are two broad issues that may be
754different about writing apps for Android:
755<ul>
756<li>Some virtual machines, such as the JVM or .net runtime, act as a security
757boundary, isolating code from the underlying operating system capabilities.  On
758Android, the Dalvik VM is not a security boundary&mdash;the application sandbox is
759implemented at the OS level, so Dalvik can interoperate with native code in the
760same application without any security constraints.</li>
761
762<li>Given the limited storage on mobile devices, it’s common for developers
763to want to build modular applications and use dynamic class loading.  When
764doing this, consider both the source where you retrieve your application logic
765and where you store it locally. Do not use dynamic class loading from sources
766that are not verified, such as unsecured network sources or external storage,
767because that code might be modified to include malicious behavior.</li>
768</ul>
769
770
771
772<h2 id="Native">Security in native code</h2>
773
774<p>In general, you should use the Android SDK for
775application development, rather than using native code with the
776<a href="{@docRoot}tools/sdk/ndk/index.html">Android NDK</a>.  Applications built
777with native code are more complex, less portable, and more like to include
778common memory-corruption errors such as buffer overflows.</p>
779
780<p>Android is built using the Linux kernel, and being familiar with Linux
781development security best practices is especially useful if you are
782using native code. Linux security practices are beyond the scope of this document,
783but one of the most popular resources is <a href="http://www.dwheeler.com/secure-programs"
784 class="external-link">Secure Programming HOWTO - Creating Secure Software</a>.</p>
785
786<p>An important difference between Android and most Linux environments is the
787Application Sandbox.  On Android, all applications run in the Application
788Sandbox, including those written with native code.  At the most basic level, a
789good way to think about it for developers familiar with Linux is to know that
790every application is given a unique <acronym title="User Identifier">UID</acronym>
791with very limited permissions. This is discussed in more detail in the <a
792href="http://source.android.com/tech/security/index.html">Android Security
793Overview</a>, and you should be familiar with application permissions even if
794you are using native code.</p>
795