1 page.title=Security Tips 2 page.article=true 3 @jd:body 4 5 <div id="tb-wrapper"> 6 <div id="tb"> 7 <h2>In this document</h2> 8 <ol class="nolist"> 9 <li><a href="#StoringData">Storing Data</a></li> 10 <li><a href="#Permissions">Using Permissions</a></li> 11 <li><a href="#Networking">Using Networking</a></li> 12 <li><a href="#InputValidation">Performing Input Validation</a></li> 13 <li><a href="#UserData">Handling User Data</a></li> 14 <li><a href="#WebView">Using WebView</a></li> 15 <li><a href="#Crypto">Using Cryptography</a></li> 16 <li><a href="#IPC">Using Interprocess Communication</a></li> 17 <li><a href="#DynamicCode">Dynamically Loading Code</a></li> 18 <li><a href="#Dalvik">Security in a Virtual Machine</a></li> 19 <li><a href="#Native">Security in Native Code</a></li> 20 </ol> 21 <h2>See also</h2> 22 <ul> 23 <li><a href="http://source.android.com/tech/security/index.html">Android 24 Security Overview</a></li> 25 <li><a href="{@docRoot}guide/topics/security/permissions.html">Permissions</a></li> 26 </ul> 27 </div></div> 28 29 30 <p>Android has security features built 31 into the operating system that significantly reduce the frequency and impact of 32 application security issues. The system is designed so you can typically build your apps with 33 default 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 36 include: 37 <ul> 38 <li>The Android Application Sandbox, which isolates your app data and code execution 39 from other apps.</li> 40 <li>An application framework with robust implementations of common 41 security 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 44 calloc, and Linux mmap_min_addr to mitigate risks associated with common memory 45 management errors.</li> 46 <li>An encrypted filesystem that can be enabled to protect data on lost or 47 stolen 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 53 security best practices in this document. Following these practices as general coding habits 54 will reduce the likelihood of inadvertently introducing security issues that 55 adversely 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 62 that you save on the device is accessible to other apps. There are three fundamental 63 ways 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 68 href="{@docRoot}guide/topics/data/data-storage.html#filesInternal">internal 69 storage</a> are accessible only to your app. This 70 protection is implemented by Android and is sufficient for most 71 applications.</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 76 the ability to limit data access to particular applications, nor do they 77 provide any control on data format. If you want to share your data with other 78 app processes, you might instead consider using a 79 <a href="{@docRoot}guide/topics/providers/content-providers.html">content provider</a>, which 80 offers read and write permissions to other apps and can make 81 dynamic permission grants on a case-by-case basis.</p> 82 83 <p>To provide additional protection for sensitive data, you might 84 choose to encrypt local files using a key that is not directly accessible to the 85 application. For example, a key can be placed in a {@link java.security.KeyStore} 86 and protected with a user password that is not stored on the device. While this 87 does not protect data from a root compromise that can monitor the user 88 inputting the password, it can provide protection for a lost device without <a 89 href="http://source.android.com/tech/encryption/index.html">file system 90 encryption</a>.</p> 91 92 93 <h3 id="ExternalStorage">Using external storage</h3> 94 95 <p>Files created on <a 96 href="{@docRoot}guide/topics/data/data-storage.html#filesExternal">external 97 storage</a>, such as SD Cards, are globally readable and writable. Because 98 external storage can be removed by the user and also modified by any 99 application, you should not store sensitive information using 100 external storage.</p> 101 102 <p>As with data from any untrusted source, you should <a href="#InputValidation">perform input 103 validation</a> when handling data from external storage. 104 We strongly recommend that you not store executables or 105 class files on external storage prior to dynamic loading. If your app 106 does retrieve executable files from external storage, the files should be signed and 107 cryptographically 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> 113 offer a structured storage mechanism that can be limited 114 to your own application or exported to allow access by other applications. 115 If you do not intend to provide other 116 applications with access to your {@link android.content.ContentProvider}, mark them as <code><a 117 href="{@docRoot}guide/topics/manifest/provider-element.html#exported"> 118 android:exported=false</a></code> in the application manifest. Otherwise, set the <code><a 119 href="{@docRoot}guide/topics/manifest/provider-element.html#exported">android:exported</a></code> 120 attribute {@code "true"} to allow other apps to access the stored data. 121 </p> 122 123 <p>When creating a {@link android.content.ContentProvider} 124 that 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 127 within the manifest. We recommend that you limit your permissions to those 128 required to accomplish the task at hand. Keep in mind that its usually 129 easier to add permissions later to expose new functionality than it is to take 130 them away and break existing users.</p> 131 132 <p>If you are using a content provider 133 for 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 135 android:protectionLevel}</a> attribute set to {@code "signature"} protection. 136 Signature permissions do not require user confirmation, 137 so they provide a better user experience and more controlled access to the 138 content provider data when the apps accessing the data are 139 <a href="{@docRoot}tools/publishing/app-signing.html">signed</a> with 140 the same key.</p> 141 142 <p>Content providers can also provide more granular access by declaring the <a 143 href="{@docRoot}guide/topics/manifest/provider-element.html#gprmsn">{@code 144 android:grantUriPermissions}</a> attribute and using the {@link 145 android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION} and {@link 146 android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION} flags in the 147 {@link android.content.Intent} object 148 that activates the component. The scope of these permissions can be further 149 limited by the <code><a 150 href="{@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 157 potential SQL injection from untrusted sources. Note that using parameterized methods is not 158 sufficient if the <code>selection</code> argument is built by concatenating user data 159 prior to submitting it to the method.</p> 160 161 <p>Do not have a false sense of security about the write permission. Consider 162 that the write permission allows SQL statements which make it possible for some 163 data to be confirmed using creative <code>WHERE</code> clauses and parsing the 164 results. For example, an attacker might probe for presence of a specific phone 165 number in a call-log by modifying a row only if that phone number already 166 exists. If the content provider data has predictable structure, the write 167 permission 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 178 share resources and data. They do this by declaring the permissions they need for additional 179 capabilities not provided by the basic sandbox, including access to device features such as 180 the 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. 186 Not having access to sensitive permissions reduces the risk of 187 inadvertently misusing those permissions, can improve user adoption, and makes 188 your app less vulnerable for attackers. Generally, 189 if 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 192 any permissions, that is preferable. For example, rather than requesting access 193 to device information to create a unique identifier, create a <a 194 href="{@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 196 using external storage (which requires permission), store data 197 on the internal storage.</p> 198 199 <p>In addition to requesting permissions, your application can use the <a 200 href="{@docRoot}guide/topics/manifest/permission-element.html">{@code <permissions>}</a> 201 to protect IPC that is security sensitive and will be exposed to other 202 applications, such as a {@link android.content.ContentProvider}. 203 In general, we recommend using access controls 204 other than user confirmed permissions where possible because permissions can 205 be confusing for users. For example, consider using the <a 206 href="{@docRoot}guide/topics/manifest/permission-element.html#plevel">signature 207 protection level</a> on permissions for IPC communication between applications 208 provided by a single developer.</p> 209 210 <p>Do not leak permission-protected data. This occurs when your app exposes 211 data over IPC that is available only because your app has permission to access 212 that data. The clients of your app's IPC interface may not have that same 213 data-access permission. More details on the frequency and potential effects 214 of this issue appear in <a class="external-link" 215 href="https://www.usenix.org/legacy/event/sec11/tech/full_papers/Felt.pdf"> this 216 research 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 223 satisfying your security requirements. Creating a new permission is relatively 224 uncommon for most applications, because the <a 225 href="{@docRoot}reference/android/Manifest.permission.html">system-defined 226 permissions</a> cover many situations. Where appropriate, 227 perform access checks using existing permissions.</p> 228 229 <p>If you must create a new permission, consider whether you can accomplish 230 your task with a <a 231 href="{@docRoot}guide/topics/manifest/permission-element.html#plevel">"signature" 232 protection level</a>. Signature permissions are transparent 233 to the user and only allow access by applications signed by the same developer 234 as application performing the permission check.</p> 235 236 <p>If you create a permission with the <a 237 href="{@docRoot}guide/topics/manifest/permission-element.html#plevel">"dangerous" 238 protection level</a>, there are a number of complexities 239 that you need to consider: 240 <ul> 241 <li>The permission must have a string that concisely expresses to a user the 242 security 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 245 confusing or perceived as risky.</li> 246 <li>Applications may request the permission when the creator of the permission 247 has not been installed.</li> 248 </ul> 249 250 <p>Each of these poses a significant non-technical challenge for you as the developer 251 while also confusing your users, 252 which 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 261 data that is potentially private to the user. People are increasingly aware of the privacy 262 concerns of a mobile device, especially when the device performs network transactions, 263 so it's very important that your app implement all best practices toward keeping the user's 264 data 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 269 environments. The key consideration is making sure that appropriate protocols 270 are used for sensitive data, such as {@link javax.net.ssl.HttpsURLConnection} for 271 secure web traffic. We prefer use of HTTPS over HTTP anywhere that HTTPS is 272 supported on the server, because mobile devices frequently connect on networks 273 that are not secured, such as public Wi-Fi hotspots.</p> 274 275 <p>Authenticated, encrypted socket-level communication can be easily 276 implemented using the {@link javax.net.ssl.SSLSocket} 277 class. Given the frequency with which Android devices connect to unsecured 278 wireless networks using Wi-Fi, the use of secure networking is strongly 279 encouraged for all applications that communicate over the network.</p> 280 281 <p>We have seen some applications use <a 282 href="http://en.wikipedia.org/wiki/Localhost">localhost</a> network ports for 283 handling sensitive IPC. We discourage this approach since these interfaces are 284 accessible by other applications on the device. Instead, you should use an Android IPC 285 mechanism where authentication is possible such as with a {@link android.app.Service}. (Even 286 worse than using loopback is to bind to INADDR_ANY since then your application 287 may receive requests from anywhere.)</p> 288 289 <p>Also, one common issue that warrants repeating is to make sure that you do 290 not trust data downloaded from HTTP or other insecure protocols. This includes 291 validation of input in {@link android.webkit.WebView} and 292 any 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 298 user-to-user communication and is not well-suited for apps that want to transfer data. 299 Due to the limitations of SMS, we strongly recommend the use of <a 300 href="{@docRoot}google/gcm/index.html">Google Cloud Messaging</a> (GCM) 301 and 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 304 authenticated on either the network or the device. In particular, any SMS receiver 305 should expect that a malicious user may have sent the SMS to your application—Do 306 not rely on unauthenticated SMS data to perform sensitive commands. 307 Also, you should be aware that SMS may be subject to spoofing and/or 308 interception on the network. On the Android-powered device itself, SMS 309 messages are transmitted as broadcast intents, so they may be read or captured 310 by other applications that have the {@link android.Manifest.permission#READ_SMS} 311 permission.</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 320 affecting applications, regardless of what platform they run on. Android does 321 have platform-level countermeasures that reduce the exposure of applications to 322 input validation issues and you should use those features where possible. Also 323 note that selection of type-safe languages tends to reduce the likelihood of 324 input validation issues.</p> 325 326 <p>If you are using native code, then any data read from files, received over 327 the network, or received from an IPC has the potential to introduce a security 328 issue. The most common problems are <a 329 href="http://en.wikipedia.org/wiki/Buffer_overflow">buffer overflows</a>, <a 330 href="http://en.wikipedia.org/wiki/Double_free#Use_after_free">use after 331 free</a>, and <a 332 href="http://en.wikipedia.org/wiki/Off-by-one_error">off-by-one errors</a>. 333 Android provides a number of technologies like <acronym 334 title="Address Space Layout Randomization">ASLR</acronym> and <acronym 335 title="Data Execution Prevention">DEP</acronym> that reduce the 336 exploitability of these errors, but they do not solve the underlying problem. 337 You can prevent these vulneratbilities by careful handling pointers and managing 338 buffers.</p> 339 340 <p>Dynamic, string based languages such as JavaScript and SQL are also subject 341 to input validation problems due to escape characters and <a 342 href="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 345 content provider, SQL injection may be an issue. The best defense is to use 346 parameterized queries, as is discussed in the above section about <a 347 href="#ContentProviders">content providers</a>. 348 Limiting permissions to read-only or write-only can also reduce the potential 349 for harm related to SQL injection.</p> 350 351 <p>If you cannot use the security features above, we strongly recommend the use 352 of well-structured data formats and verifying that the data conforms to the 353 expected format. While blacklisting of characters or character-replacement can 354 be an effective strategy, these techniques are error-prone in practice and 355 should 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 364 sensitive or personal user data. If you have access to user data and can avoid 365 storing or transmitting the information, do not store or transmit the data. 366 Finally, consider if there is a way that your application logic can be 367 implemented using a hash or non-reversible form of the data. For example, your 368 application might use the hash of an an email address as a primary key, to 369 avoid transmitting or storing the email address. This reduces the chances of 370 inadvertently exposing data, and it also reduces the chance of attackers 371 attempting to exploit your application.</p> 372 373 <p>If your application accesses personal information such as passwords or 374 usernames, keep in mind that some jurisdictions may require you to provide a 375 privacy policy explaining your use and storage of that data. So following the 376 security best practice of minimizing access to user data may also simplify 377 compliance.</p> 378 379 <p>You should also consider whether your application might be inadvertently 380 exposing personal information to other parties such as third-party components 381 for advertising or third-party services used by your application. If you don't 382 know why a component or service requires a personal information, dont 383 provide it. In general, reducing the access to personal information by your 384 application will reduce the potential for problems in this area.</p> 385 386 <p>If access to sensitive data is required, evaluate whether that information 387 must be transmitted to a server, or whether the operation can be performed on 388 the client. Consider running any code using sensitive data on the client to 389 avoid transmitting user data.</p> 390 391 <p>Also, make sure that you do not inadvertently expose user data to other 392 application on the device through overly permissive IPC, world writable files, 393 or network sockets. This is a special case of leaking permission-protected data, 394 discussed in the <a href="#RequestingPermissions">Requesting Permissions</a> section.</p> 395 396 <p>If a <acronym title="Globally Unique Identifier">GUID</acronym> 397 is required, create a large, unique number and store it. Do not 398 use phone identifiers such as the phone number or IMEI which may be associated 399 with personal information. This topic is discussed in more detail in the <a 400 href="http://android-developers.blogspot.com/2011/03/identifying-app-installations.html">Android 401 Developer Blog</a>.</p> 402 403 <p>Be careful when writing to on-device logs. 404 In Android, logs are a shared resource, and are available 405 to an application with the {@link android.Manifest.permission#READ_LOGS} permission. 406 Even though the phone log data 407 is temporary and erased on reboot, inappropriate logging of user information 408 could 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, 418 improper use can introduce common web security issues such as <a 419 href="http://en.wikipedia.org/wiki/Cross_site_scripting">cross-site-scripting</a> 420 (JavaScript injection). Android includes a number of mechanisms to reduce 421 the scope of these potential issues by limiting the capability of {@link android.webkit.WebView} to 422 the 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()}. 426 Some sample code uses this method, which you might repurpose in production 427 application, so remove that method call if it's not required. By default, 428 {@link android.webkit.WebView} does 429 not execute JavaScript so cross-site-scripting is not possible.</p> 430 431 <p>Use {@link android.webkit.WebView#addJavascriptInterface 432 addJavaScriptInterface()} with 433 particular care because it allows JavaScript to invoke operations that are 434 normally reserved for Android applications. If you use it, expose 435 {@link android.webkit.WebView#addJavascriptInterface addJavaScriptInterface()} only to 436 web pages from which all input is trustworthy. If untrusted input is allowed, 437 untrusted JavaScript may be able to invoke Android methods within your app. In general, we 438 recommend exposing {@link android.webkit.WebView#addJavascriptInterface 439 addJavaScriptInterface()} 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 444 locally. Server-side 445 headers like <code>no-cache</code> can also be used to indicate that an application should 446 not cache particular content.</p> 447 448 <p>Devices running platforms older than Android 4.4 (API level 19) 449 use a version of {@link android.webkit webkit} that has a number of security issues. 450 As a workaround, if your app is running on these devices, it 451 should confirm that {@link android.webkit.WebView} objects display only trusted 452 content. You should also use the updatable security {@link 453 java.security.Provider Provider} object to make sure your app isnt exposed to 454 potential vulnerabilities in SSL, as described in <a 455 href="{@docRoot}training/articles/security-gms-provider.html">Updating Your 456 Security Provider to Protect Against SSL Exploits</a>. If your application must 457 render content from the open web, consider providing your own renderer so 458 you 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 464 credentials—to make phishing attacks more conspicuous, and less likely to be 465 successful. Instead use an authorization token and refresh it.</p> 466 467 <p>Where possible, username and password should not be stored on the device. 468 Instead, perform initial authentication using the username and password 469 supplied by the user, and then use a short-lived, service-specific 470 authorization token.</p> 471 472 <p>Services that will be accessible to multiple applications should be accessed 473 using {@link android.accounts.AccountManager}. If possible, use the 474 {@link android.accounts.AccountManager} class to invoke a cloud-based service and do not store 475 passwords 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} 479 before passing in any credentials, so that you do not inadvertently pass 480 credentials to the wrong application.</p> 481 482 <p>If credentials are to be used only by applications that you create, then you 483 can verify the application which accesses the {@link android.accounts.AccountManager} using 484 {@link android.content.pm.PackageManager#checkSignatures checkSignature()}. 485 Alternatively, 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 495 encryption, and providing secure communications channels, Android provides a 496 wide array of algorithms for protecting data using cryptography.</p> 497 498 <p>In general, try to use the highest level of pre-existing framework 499 implementation that can support your use case. If you need to securely 500 retrieve a file from a known location, a simple HTTPS URI may be adequate and 501 requires no knowledge of cryptography. If you need a secure 502 tunnel, 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 506 recommend that you <em>not</em> implement your own cryptographic algorithms. Use 507 existing cryptographic algorithms such as those in the implementation of AES or 508 RSA provided in the {@link javax.crypto.Cipher} class.</p> 509 510 <p>Use a secure random number generator, {@link java.security.SecureRandom}, 511 to initialize any cryptographic keys, {@link javax.crypto.KeyGenerator}. 512 Use of a key that is not generated with a secure random 513 number generator significantly weakens the strength of the algorithm, and may 514 allow 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 518 provides a mechanism for long term storage and retrieval of cryptographic 519 keys.</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 528 techniques such as network sockets and shared files. We strongly encourage you to instead 529 use Android system functionality for IPC such as {@link android.content.Intent}, 530 {@link android.os.Binder} or {@link android.os.Messenger} with a {@link 531 android.app.Service}, and {@link android.content.BroadcastReceiver}. 532 The Android IPC mechanisms allow you to verify the identity of 533 the application connecting to your IPC and set security policy for each IPC 534 mechanism.</p> 535 536 <p>Many of the security elements are shared across IPC mechanisms. 537 If 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, 539 such as for the <a 540 href="{@docRoot}guide/topics/manifest/service-element.html#exported">{@code <service>}</a> 541 element. This is useful for applications that consist of multiple processes 542 within the same UID, or if you decide late in development that you do not 543 actually want to expose functionality as IPC but you dont want to rewrite 544 the code.</p> 545 546 <p>If your IPC is intended to be accessible to other applications, you can 547 apply a security policy by using the <a 548 href="{@docRoot}guide/topics/manifest/permission-element.html">{@code <permission>}</a> 549 element. If IPC is between your own separate apps that are signed with the same key, 550 it is preferable to use {@code "signature"} level permission in the <a 551 href="{@docRoot}guide/topics/manifest/permission-element.html#plevel">{@code 552 android: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. 560 Depending on your application requirements, you might use {@link 561 android.content.Context#sendBroadcast sendBroadcast()}, {@link 562 android.content.Context#sendOrderedBroadcast sendOrderedBroadcast()}, 563 or an explicit intent to a specific application component.</p> 564 565 <p>Note that ordered broadcasts can be consumed by a recipient, so they 566 may not be delivered to all applications. If you are sending an intent that must be delivered 567 to a specific receiver, then you must use an explicit intent that declares the receiver 568 by nameintent.</p> 569 570 <p>Senders of an intent can verify that the recipient has a permission 571 specifying a non-Null permission with the method call. Only applications with that 572 permission will receive the intent. If data within a broadcast intent may be 573 sensitive, you should consider applying a permission to make sure that 574 malicious applications cannot register to receive those messages without 575 appropriate permissions. In those circumstances, you may also consider 576 invoking the receiver directly, rather than raising a broadcast.</p> 577 578 <p class="note"><strong>Note:</strong> Intent filters should not be considered 579 a security feature—components 580 can be invoked with explicit intents and may not have data that would conform to the intent 581 filter. You should perform input validation within your intent receiver to 582 confirm that it is properly formatted for the invoked receiver, service, or 583 activity.</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 591 use. Each service class must have a corresponding <a 592 href="{@docRoot}guide/topics/manifest/service-element.html">{@code <service>}</a> declaration in its 593 manifest file.</p> 594 595 <p>By default, services are not exported and cannot be invoked by any other 596 application. However, if you add any intent filters to the service declaration, then it is exported 597 by default. It's best if you explicitly declare the <a 598 href="{@docRoot}guide/topics/manifest/service-element.html#exported">{@code 599 android:exported}</a> attribute to be sure it behaves as you'd like. 600 Services can also be protected using the <a 601 href="{@docRoot}guide/topics/manifest/service-element.html#prmsn">{@code android:permission}</a> 602 attribute. By doing so, other applications will need to declare 603 a corresponding <code><a 604 href="{@docRoot}guide/topics/manifest/uses-permission-element.html"><uses-permission></a> 605 </code> element in their own manifest to be 606 able to start, stop, or bind to the service.</p> 607 608 <p>A service can protect individual IPC calls into it with permissions, by 609 calling {@link android.content.Context#checkCallingPermission 610 checkCallingPermission()} before executing 611 the implementation of that call. We generally recommend using the 612 declarative permissions in the manifest, since those are less prone to 613 oversight.</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 620 preferred mechanism for RPC-style IPC in Android. They provide a well-defined 621 interface 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 624 interface specific permission checks. {@link android.os.Binder} and 625 {@link android.os.Messenger} objects are not declared within the 626 application manifest, and therefore you cannot apply declarative permissions 627 directly to them. They generally inherit permissions declared in the 628 application manifest for the {@link android.app.Service} or {@link 629 android.app.Activity} within which they are 630 implemented. If you are creating an interface that requires authentication 631 and/or access controls, those controls must be 632 explicitly added as code in the {@link android.os.Binder} or {@link android.os.Messenger} 633 interface.</p> 634 635 <p>If providing an interface that does require access controls, use {@link 636 android.content.Context#checkCallingPermission checkCallingPermission()} 637 to verify whether the 638 caller has a required permission. This is especially important 639 before accessing a service on behalf of the caller, as the identify of your 640 application is passed to other interfaces. If invoking an interface provided 641 by a {@link android.app.Service}, the {@link 642 android.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 645 useful to use the {@link android.os.Binder#clearCallingIdentity clearCallingIdentity()} 646 to 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 656 an {@link android.content.Intent}.</p> 657 658 <p>By default, receivers are exported and can be invoked by any other 659 application. If your {@link android.content.BroadcastReceiver} 660 is intended for use by other applications, you 661 may want to apply security permissions to receivers using the <code><a 662 href="{@docRoot}guide/topics/manifest/receiver-element.html"> 663 <receiver></a></code> element within the application manifest. This will 664 prevent applications without appropriate permissions from sending an intent to 665 the {@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. 677 Doing so significantly increases the likelihood of application compromise due 678 to code injection or code tampering. It also adds complexity around version 679 management and application testing. Finally, it can make it impossible to 680 verify the behavior of an application, so it may be prohibited in some 681 environments.</p> 682 683 <p>If your application does dynamically load code, the most important thing to 684 keep in mind about dynamically loaded code is that it runs with the same 685 security permissions as the application APK. The user made a decision to 686 install your application based on your identity, and they are expecting that 687 you provide any code run within the application, including code that is 688 dynamically loaded.</p> 689 690 <p>The major security risk associated with dynamically loading code is that the 691 code needs to come from a verifiable source. If the modules are included 692 directly within your APK, then they cannot be modified by other applications. 693 This 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 695 attempting to load code from insecure locations, such as downloaded from the 696 network over unencrypted protocols or from world writable locations such as 697 external storage. These locations could allow someone on the network to modify 698 the content in transit, or another application on a users device to modify the 699 content 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, 708 but many of the concerns regarding secure code in other virtual machines also apply to Android. 709 In general, you shouldn't concern yourself with security issues relating to the virtual machine. 710 Your application runs in a secure sandbox environment, so other processes on the system cannnot 711 access your code or private data.</p> 712 713 <p>If you're interested in diving deeper on the subject of virtual machine security, 714 we recommend that you familiarize yourself with some 715 existing literature on the subject. Two of the more popular resources are: 716 <ul> 717 <li><a href="http://www.securingjava.com/toc.html"> 718 http://www.securingjava.com/toc.html</a></li> 719 <li><a 720 href="https://www.owasp.org/index.php/Java_Security_Resources"> 721 https://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 725 different from other VM environments. For developers experienced with VM 726 programming in other environments, there are two broad issues that may be 727 different about writing apps for Android: 728 <ul> 729 <li>Some virtual machines, such as the JVM or .net runtime, act as a security 730 boundary, isolating code from the underlying operating system capabilities. On 731 Android, the Dalvik VM is not a security boundary—the application sandbox is 732 implemented at the OS level, so Dalvik can interoperate with native code in the 733 same application without any security constraints.</li> 734 735 <li>Given the limited storage on mobile devices, its common for developers 736 to want to build modular applications and use dynamic class loading. When 737 doing this, consider both the source where you retrieve your application logic 738 and where you store it locally. Do not use dynamic class loading from sources 739 that are not verified, such as unsecured network sources or external storage, 740 because 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 748 application development, rather than using native code with the 749 <a href="{@docRoot}tools/sdk/ndk/index.html">Android NDK</a>. Applications built 750 with native code are more complex, less portable, and more like to include 751 common memory corruption errors such as buffer overflows.</p> 752 753 <p>Android is built using the Linux kernel and being familiar with Linux 754 development security best practices is especially useful if you are going to 755 use native code. Linux security practices are beyond the scope of this document, 756 but one of the most popular resources is Secure Programming for 757 Linux and Unix HOWTO, available at <a 758 href="http://www.dwheeler.com/secure-programs"> 759 http://www.dwheeler.com/secure-programs</a>.</p> 760 761 <p>An important difference between Android and most Linux environments is the 762 Application Sandbox. On Android, all applications run in the Application 763 Sandbox, including those written with native code. At the most basic level, a 764 good way to think about it for developers familiar with Linux is to know that 765 every application is given a unique <acronym title="User Identifier">UID</acronym> 766 with very limited permissions. This is discussed in more detail in the <a 767 href="http://source.android.com/tech/security/index.html">Android Security 768 Overview</a> and you should be familiar with application permissions even if 769 you are using native code.</p> 770 771