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