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<grant-uri-permission element></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 vulnerable 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 <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 211data over IPC that is available only because your app has permission to access 212that data. The clients of your app's IPC interface may not have that same 213data-access permission. More details on the frequency and potential effects 214of this issue appear in <a class="external-link" 215href="https://www.usenix.org/legacy/event/sec11/tech/full_papers/Felt.pdf"> this 216research paper</a>, published at USENIX. 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—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<p>Devices running platforms older than Android 4.4 (API level 19) 449use a version of {@link android.webkit webkit} that has a number of security issues. 450As a workaround, if your app is running on these devices, it 451should confirm that {@link android.webkit.WebView} objects display only trusted 452content. You should also use the updatable security {@link 453java.security.Provider Provider} object to make sure your app isn’t exposed to 454potential vulnerabilities in SSL, as described in <a 455href="{@docRoot}training/articles/security-gms-provider.html">Updating Your 456Security Provider to Protect Against SSL Exploits</a>. If your application must 457render content from the open web, consider providing your own renderer so 458you can keep it up to date with the latest security patches.</p> 459 460 461<h3 id="Credentials">Handling Credentials</h3> 462 463<p>In general, we recommend minimizing the frequency of asking for user 464credentials—to make phishing attacks more conspicuous, and less likely to be 465successful. Instead use an authorization token and refresh it.</p> 466 467<p>Where possible, username and password should not be stored on the device. 468Instead, perform initial authentication using the username and password 469supplied by the user, and then use a short-lived, service-specific 470authorization token.</p> 471 472<p>Services that will be accessible to multiple applications should be accessed 473using {@link android.accounts.AccountManager}. If possible, use the 474{@link android.accounts.AccountManager} class to invoke a cloud-based service and do not store 475passwords on the device.</p> 476 477<p>After using {@link android.accounts.AccountManager} to retrieve an 478{@link android.accounts.Account}, {@link android.accounts.Account#CREATOR} 479before passing in any credentials, so that you do not inadvertently pass 480credentials to the wrong application.</p> 481 482<p>If credentials are to be used only by applications that you create, then you 483can verify the application which accesses the {@link android.accounts.AccountManager} using 484{@link android.content.pm.PackageManager#checkSignatures checkSignature()}. 485Alternatively, if only one application will use the credential, you might use a 486{@link java.security.KeyStore} for storage.</p> 487 488 489 490 491 492<h2 id="Crypto">Using Cryptography</h2> 493 494<p>In addition to providing data isolation, supporting full-filesystem 495encryption, and providing secure communications channels, Android provides a 496wide array of algorithms for protecting data using cryptography.</p> 497 498<p>In general, try to use the highest level of pre-existing framework 499implementation that can support your use case. If you need to securely 500retrieve a file from a known location, a simple HTTPS URI may be adequate and 501requires no knowledge of cryptography. If you need a secure 502tunnel, consider using {@link javax.net.ssl.HttpsURLConnection} or 503{@link javax.net.ssl.SSLSocket}, rather than writing your own protocol.</p> 504 505<p>If you do find yourself needing to implement your own protocol, we strongly 506recommend that you <em>not</em> implement your own cryptographic algorithms. Use 507existing cryptographic algorithms such as those in the implementation of AES or 508RSA provided in the {@link javax.crypto.Cipher} class.</p> 509 510<p>Use a secure random number generator, {@link java.security.SecureRandom}, 511to initialize any cryptographic keys, {@link javax.crypto.KeyGenerator}. 512Use of a key that is not generated with a secure random 513number generator significantly weakens the strength of the algorithm, and may 514allow offline attacks.</p> 515 516<p>If you need to store a key for repeated use, use a mechanism like 517 {@link java.security.KeyStore} that 518provides a mechanism for long term storage and retrieval of cryptographic 519keys.</p> 520 521 522 523 524 525<h2 id="IPC">Using Interprocess Communication</h2> 526 527<p>Some apps attempt to implement IPC using traditional Linux 528techniques such as network sockets and shared files. We strongly encourage you to instead 529use Android system functionality for IPC such as {@link android.content.Intent}, 530{@link android.os.Binder} or {@link android.os.Messenger} with a {@link 531android.app.Service}, and {@link android.content.BroadcastReceiver}. 532The Android IPC mechanisms allow you to verify the identity of 533the application connecting to your IPC and set security policy for each IPC 534mechanism.</p> 535 536<p>Many of the security elements are shared across IPC mechanisms. 537If your IPC mechanism is not intended for use by other applications, set the 538{@code android:exported} attribute to {@code "false"} in the component's manifest element, 539such as for the <a 540href="{@docRoot}guide/topics/manifest/service-element.html#exported">{@code <service>}</a> 541element. This is useful for applications that consist of multiple processes 542within the same UID, or if you decide late in development that you do not 543actually want to expose functionality as IPC but you don’t want to rewrite 544the code.</p> 545 546<p>If your IPC is intended to be accessible to other applications, you can 547apply a security policy by using the <a 548href="{@docRoot}guide/topics/manifest/permission-element.html">{@code <permission>}</a> 549element. If IPC is between your own separate apps that are signed with the same key, 550it is preferable to use {@code "signature"} level permission in the <a 551href="{@docRoot}guide/topics/manifest/permission-element.html#plevel">{@code 552android:protectionLevel}</a>.</p> 553 554 555 556 557<h3>Using intents</h3> 558 559<p>Intents are the preferred mechanism for asynchronous IPC in Android. 560Depending on your application requirements, you might use {@link 561android.content.Context#sendBroadcast sendBroadcast()}, {@link 562android.content.Context#sendOrderedBroadcast sendOrderedBroadcast()}, 563or an explicit intent to a specific application component.</p> 564 565<p>Note that ordered broadcasts can be “consumed” by a recipient, so they 566may not be delivered to all applications. If you are sending an intent that must be delivered 567to a specific receiver, then you must use an explicit intent that declares the receiver 568by nameintent.</p> 569 570<p>Senders of an intent can verify that the recipient has a permission 571specifying a non-Null permission with the method call. Only applications with that 572permission will receive the intent. If data within a broadcast intent may be 573sensitive, you should consider applying a permission to make sure that 574malicious applications cannot register to receive those messages without 575appropriate permissions. In those circumstances, you may also consider 576invoking the receiver directly, rather than raising a broadcast.</p> 577 578<p class="note"><strong>Note:</strong> Intent filters should not be considered 579a security feature—components 580can be invoked with explicit intents and may not have data that would conform to the intent 581filter. You should perform input validation within your intent receiver to 582confirm that it is properly formatted for the invoked receiver, service, or 583activity.</p> 584 585 586 587 588<h3 id="Services">Using services</h3> 589 590<p>A {@link android.app.Service} is often used to supply functionality for other applications to 591use. Each service class must have a corresponding <a 592href="{@docRoot}guide/topics/manifest/service-element.html">{@code <service>}</a> declaration in its 593manifest file.</p> 594 595<p>By default, services are not exported and cannot be invoked by any other 596application. However, if you add any intent filters to the service declaration, then it is exported 597by default. It's best if you explicitly declare the <a 598href="{@docRoot}guide/topics/manifest/service-element.html#exported">{@code 599android:exported}</a> attribute to be sure it behaves as you'd like. 600Services can also be protected using the <a 601href="{@docRoot}guide/topics/manifest/service-element.html#prmsn">{@code android:permission}</a> 602attribute. By doing so, other applications will need to declare 603a corresponding <code><a 604href="{@docRoot}guide/topics/manifest/uses-permission-element.html"><uses-permission></a> 605</code> element in their own manifest to be 606able to start, stop, or bind to the service.</p> 607 608<p>A service can protect individual IPC calls into it with permissions, by 609calling {@link android.content.Context#checkCallingPermission 610checkCallingPermission()} before executing 611the implementation of that call. We generally recommend using the 612declarative permissions in the manifest, since those are less prone to 613oversight.</p> 614 615 616 617<h3>Using binder and messenger interfaces</h3> 618 619<p>Using {@link android.os.Binder} or {@link android.os.Messenger} is the 620preferred mechanism for RPC-style IPC in Android. They provide a well-defined 621interface that enables mutual authentication of the endpoints, if required.</p> 622 623<p>We strongly encourage designing interfaces in a manner that does not require 624interface specific permission checks. {@link android.os.Binder} and 625{@link android.os.Messenger} objects are not declared within the 626application manifest, and therefore you cannot apply declarative permissions 627directly to them. They generally inherit permissions declared in the 628application manifest for the {@link android.app.Service} or {@link 629android.app.Activity} within which they are 630implemented. If you are creating an interface that requires authentication 631and/or access controls, those controls must be 632explicitly added as code in the {@link android.os.Binder} or {@link android.os.Messenger} 633interface.</p> 634 635<p>If providing an interface that does require access controls, use {@link 636android.content.Context#checkCallingPermission checkCallingPermission()} 637to verify whether the 638caller has a required permission. This is especially important 639before accessing a service on behalf of the caller, as the identify of your 640application is passed to other interfaces. If invoking an interface provided 641by a {@link android.app.Service}, the {@link 642android.content.Context#bindService bindService()} 643 invocation may fail if you do not have permission to access the given service. 644 If calling an interface provided locally by your own application, it may be 645useful to use the {@link android.os.Binder#clearCallingIdentity clearCallingIdentity()} 646to satisfy internal security checks.</p> 647 648<p>For more information about performing IPC with a service, see 649<a href="{@docRoot}guide/components/bound-services.html">Bound Services</a>.</p> 650 651 652 653<h3 id="BroadcastReceivers">Using broadcast receivers</h3> 654 655<p>A {@link android.content.BroadcastReceiver} handles asynchronous requests initiated by 656an {@link android.content.Intent}.</p> 657 658<p>By default, receivers are exported and can be invoked by any other 659application. If your {@link android.content.BroadcastReceiver} 660is intended for use by other applications, you 661may want to apply security permissions to receivers using the <code><a 662href="{@docRoot}guide/topics/manifest/receiver-element.html"> 663<receiver></a></code> element within the application manifest. This will 664prevent applications without appropriate permissions from sending an intent to 665the {@link android.content.BroadcastReceiver}.</p> 666 667 668 669 670 671 672 673 674<h2 id="DynamicCode">Dynamically Loading Code</h2> 675 676<p>We strongly discourage loading code from outside of your application APK. 677Doing so significantly increases the likelihood of application compromise due 678to code injection or code tampering. It also adds complexity around version 679management and application testing. Finally, it can make it impossible to 680verify the behavior of an application, so it may be prohibited in some 681environments.</p> 682 683<p>If your application does dynamically load code, the most important thing to 684keep in mind about dynamically loaded code is that it runs with the same 685security permissions as the application APK. The user made a decision to 686install your application based on your identity, and they are expecting that 687you provide any code run within the application, including code that is 688dynamically loaded.</p> 689 690<p>The major security risk associated with dynamically loading code is that the 691code needs to come from a verifiable source. If the modules are included 692directly within your APK, then they cannot be modified by other applications. 693This is true whether the code is a native library or a class being loaded using 694{@link dalvik.system.DexClassLoader}. We have seen many instances of applications 695attempting to load code from insecure locations, such as downloaded from the 696network over unencrypted protocols or from world writable locations such as 697external storage. These locations could allow someone on the network to modify 698the content in transit, or another application on a users device to modify the 699content on the device, respectively.</p> 700 701 702 703 704 705<h2 id="Dalvik">Security in a Virtual Machine</h2> 706 707<p>Dalvik is Android's runtime virtual machine (VM). Dalvik was built specifically for Android, 708but many of the concerns regarding secure code in other virtual machines also apply to Android. 709In general, you shouldn't concern yourself with security issues relating to the virtual machine. 710Your application runs in a secure sandbox environment, so other processes on the system cannnot 711access your code or private data.</p> 712 713<p>If you're interested in diving deeper on the subject of virtual machine security, 714we recommend that you familiarize yourself with some 715existing literature on the subject. Two of the more popular resources are: 716<ul> 717<li><a href="http://www.securingjava.com/toc.html"> 718http://www.securingjava.com/toc.html</a></li> 719<li><a 720href="https://www.owasp.org/index.php/Java_Security_Resources"> 721https://www.owasp.org/index.php/Java_Security_Resources</a></li> 722</ul></p> 723 724<p>This document is focused on the areas which are Android specific or 725different from other VM environments. For developers experienced with VM 726programming in other environments, there are two broad issues that may be 727different about writing apps for Android: 728<ul> 729<li>Some virtual machines, such as the JVM or .net runtime, act as a security 730boundary, isolating code from the underlying operating system capabilities. On 731Android, the Dalvik VM is not a security boundary—the application sandbox is 732implemented at the OS level, so Dalvik can interoperate with native code in the 733same application without any security constraints.</li> 734 735<li>Given the limited storage on mobile devices, it’s common for developers 736to want to build modular applications and use dynamic class loading. When 737doing this, consider both the source where you retrieve your application logic 738and where you store it locally. Do not use dynamic class loading from sources 739that are not verified, such as unsecured network sources or external storage, 740because that code might be modified to include malicious behavior.</li> 741</ul> 742 743 744 745<h2 id="Native">Security in Native Code</h2> 746 747<p>In general, we encourage developers to use the Android SDK for 748application development, rather than using native code with the 749<a href="{@docRoot}tools/sdk/ndk/index.html">Android NDK</a>. Applications built 750with native code are more complex, less portable, and more like to include 751common memory corruption errors such as buffer overflows.</p> 752 753<p>Android is built using the Linux kernel and being familiar with Linux 754development security best practices is especially useful if you are going to 755use native code. Linux security practices are beyond the scope of this document, 756but one of the most popular resources is “Secure Programming for 757Linux and Unix HOWTO”, available at <a 758href="http://www.dwheeler.com/secure-programs"> 759http://www.dwheeler.com/secure-programs</a>.</p> 760 761<p>An important difference between Android and most Linux environments is the 762Application Sandbox. On Android, all applications run in the Application 763Sandbox, including those written with native code. At the most basic level, a 764good way to think about it for developers familiar with Linux is to know that 765every application is given a unique <acronym title="User Identifier">UID</acronym> 766with very limited permissions. This is discussed in more detail in the <a 767href="http://source.android.com/tech/security/index.html">Android Security 768Overview</a> and you should be familiar with application permissions even if 769you are using native code.</p> 770 771