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