Author Archives: Scott Westover

System hardening in Android 11

In Android 11 we continue to increase the security of the Android platform. We have moved to safer default settings, migrated to a hardened memory allocator, and expanded the use of compiler mitigations that defend against classes of vulnerabilities and frustrate exploitation techniques.

Initializing memory

We’ve enabled forms of automatic memory initialization in both Android 11’s userspace and the Linux kernel. Uninitialized memory bugs occur in C/C++ when memory is used without having first been initialized to a known safe value. These types of bugs can be confusing, and even the term “uninitialized” is misleading. Uninitialized may seem to imply that a variable has a random value. In reality it isn’t random. It has whatever value was previously placed there. This value may be predictable or even attacker controlled. Unfortunately this behavior can result in a serious vulnerability such as information disclosure bugs like ASLR bypasses, or control flow hijacking via a stack or heap spray. Another possible side effect of using uninitialized values is advanced compiler optimizations may transform the code unpredictably, as this is considered undefined behavior by the relevant C standards.

In practice, uses of uninitialized memory are difficult to detect. Such errors may sit in the codebase unnoticed for years if the memory happens to be initialized with some "safe" value most of the time. When uninitialized memory results in a bug, it is often challenging to identify the source of the error, particularly if it is rarely triggered.

Eliminating an entire class of such bugs is a lot more effective than hunting them down individually. Automatic stack variable initialization relies on a feature in the Clang compiler which allows choosing initializing local variables with either zeros or a pattern.

Initializing to zero provides safer defaults for strings, pointers, indexes, and sizes. The downsides of zero init are less-safe defaults for return values, and exposing fewer bugs where the underlying code relies on zero initialization. Pattern initialization tends to expose more bugs and is generally safer for return values and less safe for strings, pointers, indexes, and sizes.

Initializing Userspace:

Automatic stack variable initialization is enabled throughout the entire Android userspace. During the development of Android 11, we initially selected pattern in order to uncover bugs relying on zero init and then moved to zero-init after a few months for increased safety. Platform OS developers can build with `AUTO_PATTERN_INITIALIZE=true m` if they want help uncovering bugs relying on zero init.

Initializing the Kernel:

Automatic stack and heap initialization were recently merged in the upstream Linux kernel. We have made these features available on earlier versions of Android’s kernel including 4.14, 4.19, and 5.4. These features enforce initialization of local variables and heap allocations with known values that cannot be controlled by attackers and are useless when leaked. Both features result in a performance overhead, but also prevent undefined behavior improving both stability and security.

For kernel stack initialization we adopted the CONFIG_INIT_STACK_ALL from upstream Linux. It currently relies on Clang pattern initialization for stack variables, although this is subject to change in the future.

Heap initialization is controlled by two boot-time flags, init_on_alloc and init_on_free, with the former wiping freshly allocated heap objects with zeroes (think s/kmalloc/kzalloc in the whole kernel) and the latter doing the same before the objects are freed (this helps to reduce the lifetime of security-sensitive data). init_on_alloc is a lot more cache-friendly and has smaller performance impact (within 2%), therefore it has been chosen to protect Android kernels.

Scudo is now Android's default native allocator

In Android 11, Scudo replaces jemalloc as the default native allocator for Android. Scudo is a hardened memory allocator designed to help detect and mitigate memory corruption bugs in the heap, such as:

Scudo does not fully prevent exploitation but it does add a number of sanity checks which are effective at strengthening the heap against some memory corruption bugs.

It also proactively organizes the heap in a way that makes exploitation of memory corruption more difficult, by reducing the predictability of the allocation patterns, and separating allocations by sizes.

In our internal testing, Scudo has already proven its worth by surfacing security and stability bugs that were previously undetected.

Finding Heap Memory Safety Bugs in the Wild (GWP-ASan)

Android 11 introduces GWP-ASan, an in-production heap memory safety bug detection tool that's integrated directly into the native allocator Scudo. GWP-ASan probabilistically detects and provides actionable reports for heap memory safety bugs when they occur, works on 32-bit and 64-bit processes, and is enabled by default for system processes and system apps.

GWP-ASan is also available for developer applications via a one line opt-in in an app's AndroidManifest.xml, with no complicated build support or recompilation of prebuilt libraries necessary.

Software Tag-Based KASAN

Continuing work on adopting the Arm Memory Tagging Extension (MTE) in Android, Android 11 includes support for kernel HWASAN, also known as Software Tag-Based KASAN. Userspace HWASAN is supported since Android 10.

KernelAddressSANitizer (KASAN) is a dynamic memory error detector designed to find out-of-bound and use-after-free bugs in the Linux kernel. Its Software Tag-Based mode is a software implementation of the memory tagging concept for the kernel. Software Tag-Based KASAN is available in 4.14, 4.19 and 5.4 Android kernels, and can be enabled with the CONFIG_KASAN_SW_TAGS kernel configuration option. Currently Tag-Based KASAN only supports tagging of slab memory; support for other types of memory (such as stack and globals) will be added in the future.

Compared to Generic KASAN, Tag-Based KASAN has significantly lower memory requirements (see this kernel commit for details), which makes it usable on dog food testing devices. Another use case for Software Tag-Based KASAN is checking the existing kernel code for compatibility with memory tagging. As Tag-Based KASAN is based on similar concepts as the future in-kernel MTE support, making sure that kernel code works with Tag-Based KASAN will ease in-kernel MTE integration in the future.

Expanding existing compiler mitigations

We’ve continued to expand the compiler mitigations that have been rolled out in prior releases as well. This includes adding both integer and bounds sanitizers to some core libraries that were lacking them. For example, the libminikin fonts library and the libui rendering library are now bounds sanitized. We’ve hardened the NFC stack by implementing both integer overflow sanitizer and bounds sanitizer in those components.

In addition to the hard mitigations like sanitizers, we also continue to expand our use of CFI as an exploit mitigation. CFI has been enabled in Android’s networking daemon, DNS resolver, and more of our core javascript libraries like libv8 and the PacProcessor.

The effectiveness of our software codec sandbox

Prior to the Release of Android 10 we announced a new constrained sandbox for software codecs. We’re really pleased with the results. Thus far, Android 10 is the first Android release since the infamous stagefright vulnerabilities in Android 5.0 with zero critical-severity vulnerabilities in the media frameworks.

Thank you to Jeff Vander Stoep, Alexander Potapenko, Stephen Hines, Andrey Konovalov, Mitch Phillips, Ivan Lozano, Kostya Kortchinsky, Christopher Ferris, Cindy Zhou, Evgenii Stepanov, Kevin Deus, Peter Collingbourne, Elliott Hughes, Kees Cook and Ken Chen for their contributions to this post.

11 Weeks of Android: Privacy and Security

This blog post is part of a weekly series for #11WeeksOfAndroid. For each #11WeeksOfAndroid, we’re diving into a key area so you don’t miss anything. This week, we spotlighted Privacy and Security; here’s a look at what you should know.

mobile security illustration

Privacy and security is core to how we design Android, and with every new release we increase our investment in this space. Android 11 continues to make important strides in these areas, and this week we’ll be sharing a series of updates and resources about Android privacy and security. But first, let’s take a quick look at some of the most important changes we’ve made in Android 11 to protect user privacy and make the platform more secure.

As shared in the “All things privacy in Android 11” video, we’re giving users even more control over sensitive permissions. Throughout the development of this release, we have engaged deeply and frequently with our developer community to design these features in a balanced way - amplifying user privacy while minimizing developer impact. Let’s go over some of these features:

One-time permission: In Android 10, we introduced a granular location permission that allows users to limit access to location only when an app is in use (aka foreground only). When presented with the new runtime permissions options, users choose foreground only location more than 50% of the time. This demonstrated to us that users really wanted finer controls for permissions. So in Android 11, we’ve introduced one time permissions that let users give an app access to the device microphone, camera, or location, just that one time. As an app developer, there are no changes that you need to make to your app for it to work with one time permissions, and the app can request permissions again the next time the app is used. Learn more about building privacy-friendly apps with these new changes in this video.

Background location: In Android 10 we added a background location usage reminder so users can see how apps are using this sensitive data on a regular basis. Users who interacted with the reminder either downgraded or denied the location permission over 75% of the time. In addition, we have done extensive research and believe that there are very few legitimate use cases for apps to require access to location in the background.

In Android 11, background location will no longer be a permission that a user can grant via a run time prompt and it will require a more deliberate action. If your app needs background location, the system will ensure that the app first asks for foreground location. The app can then broaden its access to background location through a separate permission request, which will cause the system to take the user to Settings in order to complete the permission grant.

In February, we announced that Google Play developers will need to get approval to access background location in their app to prevent misuse. We're giving developers more time to make changes and won't be enforcing the policy for existing apps until 2021. Check out this helpful video to find possible background location usage in your code.

Permissions auto-reset: Most users tend to download and install over 60 apps on their device but interact with only a third of these apps on a regular basis. If users haven’t used an app that targets Android 11 for an extended period of time, the system will “auto-reset” all of the granted runtime permissions associated with the app and notify the user. The app can request the permissions again the next time the app is used. If you have an app that has a legitimate need to retain permissions, you can prompt users to turn this feature OFF for your app in Settings.

Data access auditing APIs: Android encourages developers to limit their access to sensitive data, even if they have been granted permission to do so. In Android 11, developers will have access to new APIs that will give them more transparency into their app’s usage of private and protected data. The APIs will enable apps to track when the system records the app’s access to private user data.

Scoped Storage: In Android 10, we introduced scoped storage which provides a filtered view into external storage, giving access to app-specific files and media collections. This change protects user privacy by limiting broad access to shared storage in many ways including changing the storage permission to only give read access to photos, videos and music and improving app storage attribution. Since Android 10, we’ve incorporated developer feedback and made many improvements to help developers adopt scoped storage, including: updated permission UI to enhance user experience, direct file path access to media to improve compatibility with existing libraries, updated APIs for modifying media, Manage External Storage permission to enable select use cases that need broad files access, and protected external app directories. In Android 11, scoped storage will be mandatory for all apps that target API level 30. Learn more in this video and check out the developer documentation for further details.

Google Play system updates: Google Play system updates were introduced with Android 10 as part of Project Mainline. Their main benefit is to increase the modularity and granularity of platform subsystems within Android so we can update core OS components without needing a full OTA update from your phone manufacturer. Earlier this year, thanks to Project Mainline, we were able to quickly fix a critical vulnerability in the media decoding subsystem. Android 11 adds new modules, and maintains the security properties of existing ones. For example, Conscrypt, which provides cryptographic primitives, maintained its FIPS validation in Android 11 as well.

BiometricPrompt API: Developers can now use the BiometricPrompt API to specify the biometric authenticator strength required by their app to unlock or access sensitive parts of the app. We are planning to add this to the Jetpack Biometric library to allow for backward compatibility and will share further updates on this work as it progresses.

Identity Credential API: This will unlock new use cases such as mobile drivers licences, National ID, and Digital ID. It’s being built by our security team to ensure this information is stored safely, using security hardware to secure and control access to the data, in a way that enhances user privacy as compared to traditional physical documents. We’re working with various government agencies and industry partners to make sure that Android 11 is ready for such digital-first identity experiences.

Thank you for your flexibility and feedback as we continue to build an increasingly more private and secure platform. You can learn about more features in the Android 11 Beta developer site. You can also learn about general best practices related to privacy and security.

Please follow Android Developers on Twitter and Youtube to catch helpful content and materials in this area all this week.

Resources

You can find the entire playlist of #11WeeksOfAndroid video content here, and learn more about each week here. We’ll continue to spotlight new areas each week, so keep an eye out and follow us on Twitter and YouTube. Thanks so much for letting us be a part of this experience with you!

Enhanced Safe Browsing Protection now available in Chrome

Over the past few years we’ve seen threats on the web becoming increasingly sophisticated. Phishing sites rotate domains very quickly to avoid being blocked, and malware campaigns are directly targeting at-risk users. We’ve realized that to combat these most effectively, security cannot be one-size-fits-all anymore: That’s why today we are announcing Enhanced Safe Browsing protection in Chrome, a new option for users who require or want a more advanced level of security while browsing the web.

Turning on Enhanced Safe Browsing will substantially increase protection from dangerous websites and downloads. By sharing real-time data with Google Safe Browsing, Chrome can proactively protect you against dangerous sites. If you’re signed in, Chrome and other Google apps you use (Gmail, Drive, etc) will be able to provide improved protection based on a holistic view of threats you encounter on the web and attacks against your Google Account. In other words, we’re bringing the intelligence of Google’s cutting-edge security tools directly into your browser.

Over the next year, we’ll be adding even more protections to this mode, including tailored warnings for phishing sites and file downloads and cross-product alerts.

Building upon Safe Browsing

Safe Browsing’s blocklist API is an existing security protocol that protects billions of devices worldwide. Every day, Safe Browsing discovers thousands of new unsafe sites and adds them to the blocklist API that is shared with the web industry. Chrome checks the URL of each site you visit or file you download against a local list, which is updated approximately every 30 minutes. Increasingly, some sophisticated phishing sites slip through that 30-minute refresh window by switching domains very quickly.

This protocol is designed so that Google cannot determine the actual URL Chrome visited from this information, and thus by necessity the same verdict is returned regardless of the user’s situation. This means Chrome can’t adjust protection based on what kinds of threats a particular user is seeing or the type of sites they normally visit. So while the Safe Browsing blocklist API remains very powerful and will continue to protect users, we’ve been looking for ways to provide more proactive and tailored protections.

How Enhanced Safe Browsing works

When you switch to Enhanced Safe Browsing, Chrome will share additional security data directly with Google Safe Browsing to enable more accurate threat assessments. For example, Chrome will check uncommon URLs in real time to detect whether the site you are about to visit may be a phishing site. Chrome will also send a small sample of pages and suspicious downloads to help discover new threats against you and other Chrome users.

If you are signed in to Chrome, this data is temporarily linked to your Google Account. We do this so that when an attack is detected against your browser or account, Safe Browsing can tailor its protections to your situation. In this way, we can provide the most precise protection without unnecessary warnings. After a short period, Safe Browsing anonymizes this data so it is no longer connected to your account.

You can opt in to this mode by visiting Privacy and Security settings > Security > and selecting the “Enhanced protection” mode under Safe Browsing. It will be rolled out gradually in M83 on desktop platforms, with Android support coming in a future release. Enterprise administrators can control this setting via the SafeBrowsingProtectionLevel policy.

Tailored protections

Chrome’s billions of users are incredibly diverse, with a full spectrum of needs and perspectives in security and privacy. We will continue to invest in both Standard and Enhanced Safe Browsing with the goal to expand Chrome’s security offerings to cover all users.

How Google Play Protect kept users safe in 2019


Through 2019, Google Play Protect continued to improve the security for 2.5 billion Android devices. Built into Android, Play Protect scans over 100 billion apps every day for malware and other harmful apps. This past year, Play Protect prevented over 1.9 billion malware installs from unknown sources. Throughout 2019 there were many improvements made to Play Protect to bring the best of Google to Android devices to keep users safe. Some of the new features launched in 2019 include:
Advanced similarity detection
Play Protect now warns you about variations of known malware right on the device. On-device protections warn users about Potentially Harmful Apps (PHAs) at install time for a faster response. Since October 2019, Play Protect issued 380,000 warnings for install attempts using this system.
Warnings for apps targeting lower Android versions
Malware developers intentionally target devices running long outdated versions of Android to abuse exploits that have recently been patched. In 2018, Google Play started requiring new apps and app updates be built for new versions of the Android OS. This strategy ensures that users downloading apps from Google Play recieve apps that take advantage of the latest privacy and security improvements in the OS.
In 2019, we improved on this strategy with warnings to the user. Play Protect now notifies users when they install an app that is designed for outdated versions. The user can then make an informed decision to proceed with the installation or stop the app from being installed so they can look for an alternative that target the most current version of Android.
Uploading rare apps for scanning
The Android app ecosystem is growing at an exponential rate. Millions of new app versions are created and shared outside of Google Play daily posing a unique scaling challenge. Knowledge of new and rare apps is essential to provide the best protection possible.
We added a new feature that lets users help the fight against malware by sending apps Play Protect hasn't seen before for scanning during installation. The upload to Google’s scanning services preserves the privacy of the user and enables Play Protect to improve the protection for all users.
Integration with Google’s Files app
Google’s Files app is used by hundreds of millions of people every month to manage the storage on their device, share files safely, and clean up clutter and duplicate files. This year, we integrated Google Play Protect notifications within the app so that users are prompted to scan and remove any harmful applications that may be installed.
Play Protect visual updates
The Google Play Store has over 2 billion monthly active users coming to safely find the right app, game, and other digital content. This year the team was excited to roll out a complete visual redesign. With this change, Play Protect made several user-facing updates to deliver a cleaner, more prominent experience including a reminder to enable app-scanning in My apps & games to improve security.
The mobile threat landscape is always changing and so Google Play Protect must keep adapting and improving to protect our users. Visit developers.google.com/android/play-protect to stay informed on all the new exciting features and improvements being added to Google Play Protect.
Acknowledgements: Aaron Josephs, Ben Gruver, James Kelly, Rodrigo Farell, Wei Jin and William Luh

FuzzBench: Fuzzer Benchmarking as a Service


We are excited to launch FuzzBench, a fully automated, open source, free service for evaluating fuzzers. The goal of FuzzBench is to make it painless to rigorously evaluate fuzzing research and make fuzzing research easier for the community to adopt.
Fuzzing is an important bug finding technique. At Google, we’ve found tens of thousands of bugs (1, 2) with fuzzers like libFuzzer and AFL. There are numerous research papers that either improve upon these tools (e.g. MOpt-AFL, AFLFast, etc) or introduce new techniques (e.g. Driller, QSYM, etc) for bug finding. However, it is hard to know how well these new tools and techniques generalize on a large set of real world programs. Though research normally includes evaluations, these often have shortcomings—they don't use a large and diverse set of real world benchmarks, use few trials, use short trials, or lack statistical tests to illustrate if findings are significant. This is understandable since full scale experiments can be prohibitively expensive for researchers. For example, a 24-hour, 10-trial, 10 fuzzer, 20 benchmark experiment would require 2,000 CPUs to complete in a day.
To help solve these issues the OSS-Fuzz team is launching FuzzBench, a fully automated, open source, free service. FuzzBench provides a framework for painlessly evaluating fuzzers in a reproducible way. To use FuzzBench, researchers can simply integrate a fuzzer and FuzzBench will run an experiment for 24 hours with many trials and real world benchmarks. Based on data from this experiment, FuzzBench will produce a report comparing the performance of the fuzzer to others and give insights into the strengths and weaknesses of each fuzzer. This should allow researchers to focus more of their time on perfecting techniques and less time setting up evaluations and dealing with existing fuzzers.
Integrating a fuzzer with FuzzBench is simple as most integrations are less than 50 lines of code (example). Once a fuzzer is integrated, it can fuzz almost all 250+ OSS-Fuzz projects out of the box. We have already integrated ten fuzzers, including AFL, LibFuzzer, Honggfuzz, and several academic projects such as QSYM and Eclipser.
Reports include statistical tests to give an idea how likely it is that performance differences between fuzzers are simply due to chance, as well as the raw data so researchers can do their own analysis. Performance is determined by the amount of covered program edges, though we plan on adding crashes as a performance metric. You can view a sample report here.
How to Participate
Our goal is to develop FuzzBench with community contributions and input so that it becomes the gold standard for fuzzer evaluation. We invite members of the fuzzing research community to contribute their fuzzers and techniques, even while they are in development. Better evaluations will lead to more adoption and greater impact for fuzzing research.
We also encourage contributions of better ideas and techniques for evaluating fuzzers. Though we have made some progress on this problem, we have not solved it and we need the community’s help in developing these best practices.
Please join us by contributing to the FuzzBench repo on GitHub.

Helping Developers with Permission Requests


User trust is critical to the success of developers of every size. On the Google Play Store, we aim to help developers boost the trust of their users, by surfacing signals in the Developer Console about how to improve their privacy posture. Towards this aim, we surface a message to developers when we think their app is asking for permission that is likely unnecessary.
This is important because numerous studies have shown that user trust can be affected when the purpose of a permission is not clear.1 In addition, research has shown that when users are given a choice between similar apps, and one of them requests fewer permissions than the other, they choose the app with fewer permissions.2
Determining whether or not a permission request is necessary can be challenging. Android developers request permissions in their apps for many reasons - some related to core functionality, and others related to personalization, testing, advertising, and other factors. To do this, we identify a peer set of apps with similar functionality and compare a developer’s permission requests to that of their peers. If a very large percentage of these similar apps are not asking for a permission, and the developer is, we then let the developer know that their permission request is unusual compared to their peers. Our determination of the peer set is more involved than simply using Play Store categories. Our algorithm combines multiple signals that feed Natural Language Processing (NLP) and deep learning technology to determine this set. A full explanation of our method is outlined in our recent publication, entitled “Reducing Permissions Requests in Mobile Apps” that appeared in the Internet Measurement Conference (IMC) in October 2019.3 (Note that the threshold for surfacing the warning signal, as stated in this paper, is subject to change.)
We surface this information to developers in the Play Console and we let the developer make the final call as to whether or not the permission is truly necessary. It is possible that the developer has a feature unlike all of its peers. Once a developer removes a permission, they won’t see the warning any longer. Note that the warning is based on our computation of the set of peer apps similar to the developers. This is an evolving set, frequently recomputed, so the message may go away if there is an underlying change to the set of peers apps and their behavior. Similarly, even if a developer is not currently seeing a warning about a permission, they might in the future if the underlying peer set and its behavior changes. An example warning is depicted below.

This warning also helps to remind developers that they are not obligated to include all of the permission requests occurring within the libraries they include inside their apps. We are pleased to say that in the first year after deployment of this advice signal nearly 60% of warned apps removed permissions. Moreover, this occurred across all Play Store categories and all app popularity levels. The breadth of this developer response impacted over 55 billion app installs.3 This warning is one component of Google’s larger strategy to help protect users and help developers achieve good security and privacy practices, such as Project Strobe, our guidelines on permissions best practices, and our requirements around safe traffic handling.
Acknowledgements
Giles Hogben, Android Play Dashboard and Pre-Launch Report teams

References

[1] Modeling Users’ Mobile App Privacy Preferences: Restoring Usability in a Sea of Permission Settings, by J. Lin B. Liu, N. Sadeh and J. Hong. In Proceedings of Usenix Symposium on Privacy & Security (SOUPS) 2014.
[2] Using Personal Examples to Improve Risk Communication for Security & Privacy Decisions, by M. Harbach, M. Hettig, S. Weber, and M. Smith. In Proceedings of the SIGCHI Conference on Human Computing Factors in Computing Systems, 2014.
[3] Reducing Permission Requests in Mobile Apps, by S. T. Peddinti, I. Bilogrevic, N. Taft, M Pelikan, U. Erlingsson, P. Anthonysamy and G. Hogben. In Proceedings of ACM Internet Measurement Conference (IMC) 2019.

Data Encryption on Android with Jetpack Security

Posted by Jon Markoff, Staff Developer Advocate, Android Security

Illustration by Virginia Poltrack

Have you ever tried to encrypt data in your app? As a developer, you want to keep data safe, and in the hands of the party intended to use. But if you’re like most Android developers, you don’t have a dedicated security team to help encrypt your app’s data properly. By searching the web to learn how to encrypt data, you might get answers that are several years out of date and provide incorrect examples.

The Jetpack Security (JetSec) crypto library provides abstractions for encrypting Files and SharedPreferences objects. The library promotes the use of the AndroidKeyStore while using safe and well-known cryptographic primitives. Using EncryptedFile and EncryptedSharedPreferences allows you to locally protect files that may contain sensitive data, API keys, OAuth tokens, and other types of secrets.

Why would you want to encrypt data in your app? Doesn’t Android, since 5.0, encrypt the contents of the user's data partition by default? It certainly does, but there are some use cases where you may want an extra level of protection. If your app uses shared storage, you should encrypt the data. In the app home directory, your app should encrypt data if your app handles sensitive information including but not limited to personally identifiable information (PII), health records, financial details, or enterprise data. When possible, we recommend that you tie this information to biometrics for an extra level of protection.

Jetpack Security is based on Tink, an open-source, cross-platform security project from Google. Tink might be appropriate if you need general encryption, hybrid encryption, or something similar. Jetpack Security data structures are fully compatible with Tink.

Key Generation

Before we jump into encrypting your data, it’s important to understand how your encryption keys will be kept safe. Jetpack Security uses a master key, which encrypts all subkeys that are used for each cryptographic operation. JetSec provides a recommended default master key in the MasterKeys class. This class uses a basic AES256-GCM key which is generated and stored in the AndroidKeyStore. The AndroidKeyStore is a container which stores cryptographic keys in the TEE or StrongBox, making them hard to extract. Subkeys are stored in a configurable SharedPreferences object.

Primarily, we use the AES256_GCM_SPEC specification in Jetpack Security, which is recommended for general use cases. AES256-GCM is symmetric and generally fast on modern devices.


val keyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)

For apps that require more configuration, or handle very sensitive data, it’s recommended to build your KeyGenParameterSpec, choosing options that make sense for your use. Time-bound keys with BiometricPrompt can provide an extra level of protection against rooted or compromised devices.

Important options:

  • userAuthenticationRequired() and userAuthenticationValiditySeconds() can be used to create a time-bound key. Time-bound keys require authorization using BiometricPrompt for both encryption and decryption of symmetric keys.
  • unlockedDeviceRequired() sets a flag that helps ensure key access cannot happen if the device is not unlocked. This flag is available on Android Pie and higher.
  • Use setIsStrongBoxBacked(), to run crypto operations on a stronger separate chip. This has a slight performance impact, but is more secure. It’s available on some devices that run Android Pie or higher.

Note: If your app needs to encrypt data in the background, you should not use time-bound keys or require that the device is unlocked, as you will not be able to accomplish this without a user present.


// Custom Advanced Master Key
val advancedSpec = KeyGenParameterSpec.Builder(
"master_key",
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
).apply {
setBlockModes(KeyProperties.BLOCK_MODE_GCM)
setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
setKeySize(256)
setUserAuthenticationRequired(true)
setUserAuthenticationValidityDurationSeconds(15) // must be larger than 0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
setUnlockedDeviceRequired(true)
setIsStrongBoxBacked(true)
}
}.build()

val advancedKeyAlias = MasterKeys.getOrCreate(advancedSpec)

Unlocking time-bound keys

You must use BiometricPrompt to authorize the device if your key was created with the following options:

  • userAuthenticationRequired is true
  • userAuthenticationValiditySeconds > 0

After the user authenticates, the keys are unlocked for the amount of time set in the validity seconds field. The AndroidKeystore does not have an API to query key settings, so your app must keep track of these settings. You should build your BiometricPrompt instance in the onCreate() method of the activity where you present the dialog to the user.

BiometricPrompt code to unlock time-bound keys

// Activity.onCreate

val promptInfo = PromptInfo.Builder()
.setTitle("Unlock?")
.setDescription("Would you like to unlock this key?")
.setDeviceCredentialAllowed(true)
.build()

val biometricPrompt = BiometricPrompt(
this, // Activity
ContextCompat.getMainExecutor(this),
authenticationCallback
)

private val authenticationCallback = object : AuthenticationCallback() {
override fun onAuthenticationSucceeded(
result: AuthenticationResult
) {
super.onAuthenticationSucceeded(result)
// Unlocked -- do work here.
}
override fun onAuthenticationError(
errorCode: Int, errString: CharSequence
) {
super.onAuthenticationError(errorCode, errString)
// Handle error.
}
}

To use:
biometricPrompt.authenticate(promptInfo)

Encrypt Files

Jetpack Security includes an EncryptedFile class, which removes the challenges of encrypting file data. Similar to File, EncryptedFile provides a FileInputStream object for reading and a FileOutputStream object for writing. Files are encrypted using Streaming AEAD, which follows the OAE2 definition. The data is divided into chunks and encrypted using AES256-GCM in such a way that it's not possible to reorder.

val secretFile = File(filesDir, "super_secret")
val encryptedFile = EncryptedFile.Builder(
secretFile,
applicationContext,
advancedKeyAlias,
FileEncryptionScheme.AES256_GCM_HKDF_4KB)
.setKeysetAlias("file_key") // optional
.setKeysetPrefName("secret_shared_prefs") // optional
.build()

encryptedFile.openFileOutput().use { outputStream ->
// Write data to your encrypted file
}

encryptedFile.openFileInput().use { inputStream ->
// Read data from your encrypted file
}

Encrypt SharedPreferences

If your application needs to save Key-value pairs - such as API keys - JetSec provides the EncryptedSharedPreferences class, which uses the same SharedPreferences interface that you’re used to.

Both keys and values are encrypted. Keys are encrypted using AES256-SIV-CMAC, which provides a deterministic cipher text; values are encrypted with AES256-GCM and are bound to the encrypted key. This scheme allows the key data to be encrypted safely, while still allowing lookups.

EncryptedSharedPreferences.create(
"my_secret_prefs",
advancedKeyAlias,
applicationContext,
PrefKeyEncryptionScheme.AES256_SIV,
PrefValueEncryptionScheme.AES256_GCM
).edit {
// Update secret values
}

More Resources

FileLocker is a sample app on the Android Security GitHub samples page. It’s a great example of how to use File encryption using Jetpack Security.

Happy Encrypting!

Disruptive ads enforcement and our new approach


As part of our ongoing efforts — along with help from newly developed technologies — today we’re announcing nearly 600 apps have been removed from the Google Play Store and banned from our ad monetization platforms, Google AdMob and Google Ad Manager, for violating our disruptive ads policy and disallowed interstitial policy.
Mobile ad fraud is an industry-wide challenge that can appear in many different forms with a variety of methods, and it has the potential to harm users, advertisers and publishers. At Google, we have dedicated teams focused on detecting and stopping malicious developers that attempt to defraud the mobile ecosystem. As part of these efforts we take action against those who create seemingly innocuous apps, but which actually violate our ads policies.
We define disruptive ads as ads that are displayed to users in unexpected ways, including impairing or interfering with the usability of device functions. While they can occur in-app, one form of disruptive ads we’ve seen on the rise is something we call out-of-context ads, which is when malicious developers serve ads on a mobile device when the user is not actually active in their app.
This is an invasive maneuver that results in poor user experiences that often disrupt key device functions and this approach can lead to unintentional ad clicks that waste advertiser spend. For example, imagine being unexpectedly served a full-screen ad when you attempt to make a phone call, unlock your phone, or while using your favorite map app’s turn-by-turn navigation.
Malicious developers continue to become more savvy in deploying and masking disruptive ads, but we’ve developed new technologies of our own to protect against this behavior. We recently developed an innovative machine-learning based approach to detect when apps show out-of-context ads, which led to the enforcement we’re announcing today.
As we move forward, we will continue to invest in new technologies to detect and prevent emerging threats that can generate invalid traffic, including disruptive ads, and to find more ways to adapt and evolve our platform and ecosystem policies to ensure that users and advertisers are protected from bad behavior.

How we fought bad apps and malicious developers in 2019


Posted by Andrew Ahn, Product Manager, Google Play + Android App Safety
[Cross-posted from the Android Developers Blog]

Google Play connects users with great digital experiences to help them be more productive and entertained, as well as providing app developers with tools to reach billions of users around the globe. Such a thriving ecosystem can only be achieved and sustained when trust and safety is one of its key foundations. Over the last few years we’ve made the trust and safety of Google Play a top priority, and have continued our investments and improvements in our abuse detection systems, policies, and teams to fight against bad apps and malicious actors.
In 2019, we continued to strengthen our policies (especially to better protect kids and families), continued to improve our developer approval process, initiated a deeper collaboration with security industry partners through the App Defense Alliance, enhanced our machine learning detection systems analyzing an app’s code, metadata, and user engagement signals for any suspicious content or behaviors, as well as scaling the number and the depth of manual reviews. The combination of these efforts have resulted in a much cleaner Play Store:
  • Google Play released a new policy in 2018 to stop apps from unnecessarily accessing privacy-sensitive SMS and Call Log data. We saw a significant, 98% decrease in apps accessing SMS and Call Log data as developers partnered with us to update their apps and protect users. The remaining 2% are comprised of apps that require SMS and Call Log data to perform their core function.
  • One of the best ways to protect users from bad apps is to keep those apps out of the Play Store in the first place. Our improved vetting mechanisms stopped over 790,000 policy-violating app submissions before they were ever published to the Play Store.
  • Similarly to our SMS and Call Log policy, we also enacted a policy to better protect families in May 2019. After putting this in place, we worked with developers to update or remove tens of thousands of apps, making the Play Store a safer place for everyone.
In addition we’ve launched a refreshed Google Play Protect experience, our built-in malware protection for Android devices. Google Play Protect scans over 100B apps everyday, providing users with information about potential security issues and actions they can take to keep their devices safe and secure. Last year, Google Play Protect also prevented more than 1.9B malware installs from non-Google Play sources.
While we are proud of what we were able to achieve in partnership with our developer community, we know there is more work to be done. Adversarial bad actors will continue to devise new ways to evade our detection systems and put users in harm's way for their own gains. Our commitment in building the world's safest and most helpful app platform will continue in 2020, and we will continue to invest in the key app safety areas mentioned in last year’s blog post:
  • Strengthening app safety policies to protect user privacy
  • Faster detection of bad actors and blocking repeat offenders
  • Detecting and removing apps with harmful content and behaviors
Our teams of passionate product managers, engineers, policy experts, and operations leaders will continue to work with the developer community to accelerate the pace of innovation, and deliver a safer app store to billions of Android users worldwide.

Protecting users from insecure downloads in Google Chrome


Today we’re announcing that Chrome will gradually ensure that secure (HTTPS) pages only download secure files. In a series of steps outlined below, we’ll start blocking "mixed content downloads" (non-HTTPS downloads started on secure pages). This move follows a plan we announced last year to start blocking all insecure subresources on secure pages.
Insecurely-downloaded files are a risk to users' security and privacy. For instance, insecurely-downloaded programs can be swapped out for malware by attackers, and eavesdroppers can read users' insecurely-downloaded bank statements. To address these risks, we plan to eventually remove support for insecure downloads in Chrome.
As a first step, we are focusing on insecure downloads started on secure pages. These cases are especially concerning because Chrome currently gives no indication to the user that their privacy and security are at risk.
Starting in Chrome 82 (to be released April 2020), Chrome will gradually start warning on, and later blocking, these mixed content downloads. File types that pose the most risk to users (e.g., executables) will be impacted first, with subsequent releases covering more file types. This gradual rollout is designed to mitigate the worst risks quickly, provide developers an opportunity to update sites, and minimize how many warnings Chrome users have to see.
We plan to roll out restrictions on mixed content downloads on desktop platforms (Windows, macOS, Chrome OS and Linux) first. Our plan for desktop platforms is as follows:

  • In Chrome 81 (released March 2020) and later:
    • Chrome will print a console message warning about all mixed content downloads.
  • In Chrome 82 (released April 2020):
    • Chrome will warn on mixed content downloads of executables (e.g. .exe).
  • In Chrome 83 (released June 2020):
    • Chrome will block mixed content executables
    • Chrome will warn on mixed content archives (.zip) and disk images (.iso).
  • In Chrome 84 (released August 2020):
    • Chrome will block mixed content executables, archives and disk images
    • Chrome will warn on all other mixed content downloads except image, audio, video and text formats.
  • In Chrome 85 (released September 2020):
    • Chrome will warn on mixed content downloads of images, audio, video, and text
    • Chrome will block all other mixed content downloads
  • In Chrome 86 (released October 2020) and beyond, Chrome will block all mixed content downloads.
Example of a potential warning
Chrome will delay the rollout for Android and iOS users by one release, starting warnings in Chrome 83. Mobile platforms have better native protection against malicious files, and this delay will give developers a head-start towards updating their sites before impacting mobile users.
Developers can prevent users from ever seeing a download warning by ensuring that downloads only use HTTPS. In the current version of Chrome Canary, or in Chrome 81 once released, developers can activate a warning on all mixed content downloads for testing by enabling the "Treat risky downloads over insecure connections as active mixed content" flag at chrome://flags/#treat-unsafe-downloads-as-active-content.
Enterprise and education customers can disable blocking on a per-site basis via the existing InsecureContentAllowedForUrls policy by adding a pattern matching the page requesting the download.
In the future, we expect to further restrict insecure downloads in Chrome. We encourage developers to fully migrate to HTTPS to avoid future restrictions and fully protect their users. Developers with questions are welcome to email us at [email protected].