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