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