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