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