Security algorithms in android

How to Secure an Android App

Introduction

The Android operating system has lots of built-in security features, such as application sandboxing, protection against buffer and integer overflow attacks, and segregated memory areas for program instructions and data. As a result, simple Android apps that don’t perform any file system or networking operations can often be considered secure by default.

If you are developing a more complex app, however, it is your responsibility to make it secure and protect the privacy of your users. In this article, I’m going to list some of the best practices you can follow to build a secure Android app that doesn’t leak data or permissions, and is, in general, less vulnerable to malicious apps that might be installed on the user’s device.

1. Use Internal Storage for Sensitive Data

Every Android app has an internal storage directory associated with it whose path is based on the package name of the app. Files inside this directory are very secure because they use the MODE_PRIVATE file creation mode by default. This means the files cannot be accessed by any other app on the device. Therefore, it is a best place to store all the sensitive data of your app in the internal storage directory.

To determine the absolute path of your app’s internal storage directory, it is recommended that you use the getFilesDir() method. Once you know its path, referencing files inside it is as simple as referencing files inside any other directory. For example, here’s how you could reference a file called myfile.dat in the internal storage directory of your app:

2. Encrypt Data on External Storage

The internal storage capacity of an Android device is often limited. Therefore, at times, you might have no choice but to store sensitive data on external storage media, such as a removable SD card.

Because data on external storage media can be directly accessed by both users and other apps on the device, it is important that you store it in an encrypted format. One of the most popular encryption algorithms used by developers today is AES, short for Advanced Encryption Standard, with a key size of 256 bits.

Writing code to encrypt and decrypt your app’s data using the javax.crypto package, which is included in the Android SDK, can be confusing. Therefore, most developers prefer using third party libraries, such as Facebook’s Conceal library, which are usually much easier to work with.

3. Use Intents for IPC

Experienced programmers who are new to Android application development often try to use sockets, named pipes, or shared files to asynchronously communicate with other apps installed on an Android device. These approaches are not only hard and inelegant, but also prone to threats. An easier and more secure approach to interprocess communication on the Android operating system is to use intents.

To send data to a specific component of an app, you must create a new instance of the Intent class and use its setComponent() method to specify both the package name of the app and the name of the component. You can then add data to it using the putExtra() method.

For example, here’s how you could send the string Hello World to an Activity called MyActivity, which belongs to an app whose package name is my.other.app:

To send data to multiple apps at once, you can send the intent as a broadcast using the sendBroadcast() method. However, by default, a broadcast can be read by any app that has an appropriately configured BroadcastReceiver .

Therefore, if you want to send sensitive information as a broadcast, you must use a custom permission whose protectionLevel is set to signature . By doing so, the Android operating system makes sure that only apps that were signed using your signing key can receive the broadcast.

Here’s a code snippet that shows you how to send the string Hello World as a secure broadcast:

Note that the above code works as expected only if the custom permission is declared and used in the manifest files of both the sender and receiver apps.

4. Use HTTPS

All communications between your app and your servers must be over an HTTPS connection, preferably using the HttpsURLConnection class. If you think using HTTP for data that is not confidential is fine, think again.

Many Android users connect to several open Wi-Fi hotspots in public areas every day. Some of those hotspots could be malicious. A malicious hotspot can easily alter the contents of HTTP traffic to make your app behave in an unexpected manner, or worse still, inject ads or exploits into it.

By using HTTPS, as long as the server is configured with a certificate issued by a trusted certificate authority, such as DigiCert or GlobalSign, you can be sure that your network traffic is secure against both eavesdropping and man-in-the-middle attacks.

If your app has a lot of networking code and you are afraid that you might unwittingly be sending some data as cleartext, you should consider using nogotofail, an open source tool built by Google to find such mistakes.

5. Use GCM Instead of SMS

Back when GCM, short for Google Cloud Messaging, didn’t exist, many developers were using SMS to push data from their servers to their apps. Today, this practice is largely gone.

If you are one of those developers who still hasn’t made the switch from SMS to GCM, you must know that the SMS protocol is neither encrypted nor safe against spoofing attacks. What’s more, an SMS can be read by any app on the user’s device that has the READ_SMS permission.

Читайте также:  Самые лучшие виджеты для андроид

GCM is a lot more secure and is the preferred way to push messages to an app because all GCM communications are encrypted. They are authenticated using regularly refreshed registration tokens on the client side and a unique API key on the server side. To learn more about GCM, you can refer to this tutorial about push notifications .

6. Avoid Asking for Personal Data

User privacy is given a lot of importance these days. In fact, there are laws, such as the European Union’s Data Protection Directive and Canada’s Personal Information Protection and Electronic Documents Act, which mandate the protection of the privacy of a user. Therefore, unless you have a good reason and a very secure infrastructure to collect, store, and transmit personal user information, you must avoid directly asking for it in your apps.

A better approach to user authentication and user profile information look up on Android is through the Google Identity Platform . Google Identity Platform allows users to quickly sign in to your app using their Google account. After a successful sign in through the platform, whenever necessary, your app can easily look up various details about the user, such as the user’s name, email address, profile photo, contacts, and more. Alternatively, you could use free services like Firebase that can manage user authentication for you.

If you must handle user credentials yourself, it is recommended that you store and transmit them in the form of secure hashes. The most straightforward way to generate different types of hashes using the Android SDK is by using the MessageDigest class.

Here’s a little code snippet that shows you how to create a hash of the string Hello World using the SHA-256 hashing function:

7. Validate User Input

On Android, invalid user input doesn’t usually lead to security issues like buffer overruns. However, if you allow users to interact with a SQLite database or a content provider that internally uses a SQLite database, you must either rigorously sanitize user input or make use of parameterized queries. Failing to do so makes your data vulnerable to SQL injection attacks.

On a similar note, user input validation and sanitization is also very important if you are using user input to dynamically generate code to run on an embedded scripting engine, such as Mozilla Rhino .

8. Use ProGuard Before Publishing

Security measures built into an Android app can be severely compromised if attackers are able to get their hands on the source code. Before you publish your app, it is recommended to make use of a tool called ProGuard, which is included in the Android SDK, to obfuscate and minify source code.

Android Studio automatically includes ProGuard in the build process if the buildType is set to release . The default ProGuard configuration available in the Android SDK’s proguard-android.txt file is sufficient for most apps. If you want to add custom rules to the configuration, you can do so inside a file named proguard-rules.pro, which is a part of every Android Studio project.

Conclusion

I hope you now have a better understanding of how to make your Android apps secure. Most of the best practices I mentioned in this article are applicable only if you are using the Android SDK to develop your apps. If you are using the Android NDK instead, you have to be a lot more careful because, while programming in the C language, you are expected to manage low-level details, such as pointers and memory allocation yourself.

To learn more about security on Android, you can refer to the AOSP security documents.

Источник

Modern Security in Android (part 2)

A fast guide to be safe

This post is related to my lastest talk about “Modern Security for Android Developers”.

Here is the list of the blogs in this series:

In the last post of this serial we talk about Google working on a new library that will be delivered on Android Jetpack: androidx.security:security-crypto
Well, the time has passed and finally, security-crypto is now in a release candidate phase!

So now is: androidx.security:security-crypto:1.0.0-rc01

You may ask, why we need to have a new library for encryption if we already have android.security.keystore, which gives us the chance to create a key of two types, an asymmetric key pair or symmetric keys, this new library uses the builder pattern provided by Keystore but in a different style, to provide safe settings for the creation of keys, taking in consideration that we need good encryption with good performance.

So in iOS, there is something called KeyChain, it stores keys and values for the users, in Android, we have KeyStore, and one of the things you need to know is that you need to create a Provider for this. The Android Keystore system lets you store cryptographic keys in a container to make it more difficult to extract from the device. Once keys are in the Keystore, they can be used for cryptographic operations with the key material remaining non-exportable. Moreover, it offers facilities to restrict when and how keys can be used, such as requiring user authentication for key use or restricting keys to be used only in certain cryptographic modes.

How does it work?

The KeyStore has two things to protect, the key itself and the “key” that is referable to the value. Using KeyStore means you will not leak any information in your app, because the Key material never enters the application process. When your application wants to perform some crypto operation, behind the cipher are fed to a system process that carries out the cryptographic operations.

Читайте также:  Отменить подписку vsco андроид

What is a hardware-backed system?

Using KeyStore you can bound this process to secure hardware, there’s so many of this but pretty much is a TEE (Trusted execution environment), that is an isolated execution domain that provides security features when this feature is enabled for a key the material is never exposed outside of secure hardware. If the Android OS is compromised or an attacker can read the device’s internal storage, the attacker may be able to use any app’s Android Keystore keys on the Android device, but not extract them from the device.

The problem of encryption in Android

Somehow, the clarity of encryption and decryption process was not clear enough, the amount of an algorithm supported for different SDK versions of android and the number of bytes supported by these algorithms were too much information. For example, the use of Keychain API is about system-wide credentials. When an app requests the use of any credential, users get to choose, which credentials an app can access. But the Keystore provider lets an individual app store the credentials that only the app itself can access.

KeyStore was introduced in the API 1 of Android, but the Android KeyStore Provider was introduced until API 18, later on with API 28 Google introduced StrongBox for devices with a Secure Chip, even though the TEE mentioned solution is good enough, this mechanism of using a Secure Element (SE) is the most secure one since it is based on a different chip (CPU, memory, storage) designed for security purposes, this will increase the time of the operations but is probably the most secure way to do it.

In the next gist, you can see how to create a self-signed certificate and a key to start using it

What makes androidx.security different?

It is not that KeyStore and Jetpack Security are different they are a complement of each other, the new library uses KeyStore to implement a two steps operation system of Keys and Master keys with the addition that you can use it to encrypt easily a file or a shared-preference.

To start using Jetpack security you can check the next gist:

This creates the master key that you need for the keysets, MasterKeys is a helper class that allows the developer to create a master key and then gets an alias for it, the recommendation is to use the algorithm AES256-GCM that generates a symmetric key, but you can define your own key generation parameter specification, exactly like the KeyStore API in the top, including time outs, strongbox, and biometric prompts that will be discussed later on in this serial.

For the next part, we will discuss the Files and Shared Preferences you can use in Jetpack Security

This is all for this part of the post, If you need help:

Источник

Security algorithms in android

Is Your App Ready To Get Live?

This repo is created to mention security measures before making your application live

Table of Content

  1. SSL Pinning
  2. Native code for securing keys and implementation
  3. Root Access
  4. Obfuscation
  5. Encryption of Local Storage
  6. No use of implicit broadcast
  7. MediaProjection: ( Screenshots and screen protecting)
  8. Android Component Hijacking via Intent
  9. No Encryption Under Https
  10. Add Custom Permissions to protect android components
  11. Disable Stacktrace in Release Mode
  12. Android 10 Security Features (API Level 29)

SSL Pinning is used to prevent MITM.

What is an MITM attack?

Man in the Middle, abbreviated as (MITM), is where the attacker tries to intercept the communication between Client and Server. It gives the attacker full control of the sensitive data which is being passed and to manipulate it in anyway they want. In this attack the sender and receiver are unaware that they are being monitored or their session is being intercepted by a third person. This attack is also referred as session high-jacking

Check if pinned certificate is working ?

Applications should make sure that they do not send sensitive information to log output. If the app includes a third party library, the developer should make sure that the library does not send sensitive information to log output. One common solution is for an application to declare and use a custom log class, so that log output is automatically turned on/off based on Debug/Release. Developers can use ProGuard to delete specific method calls. This assumes that the method contains no side effects. Never use HTTP URL to download data. Instead, create a valid HTTPS request through which only sensitive data can be downloaded.

2) Native Code to hide hard coded keys

Getting 2D array keys in NDK( in C):

Put your secrets in jni code, add some variable code to make your libraries bigger and more difficult to decompile. You might also split key string in few parts and keep them in various places

Root Access, is when a device user has access to unlimited control over device. Its file system, OS (Roms), themes, systems apps etc. Normally, devices are locked by OEMs and Carriers depending on the features they want to cater to the consumers. This may cause device to perform below par when its on-board specifications allows it to do more. Custom Roms for more features and improved battery life is one of the most common reason to root. But it gives a serious headache to app developers if the app is using features like database or file storage.

Generally, app’s internal data directory cannot be accessed on devices (unless its debug version, which can be accessed from Android Studio/DDMS tools for testing purposes). This is the directory where the app’s critical information like database and preferences files are saved.

The purpose of obfuscation is to reduce your app size by shortening the names of your app’s classes, methods, and fields. If your code relies on predictable naming for your app’s methods and classes—when using reflection, for example, you should treat those signatures as entry points and specify keep rules for them. Use Proguard/Dexguard as a tool for obfuscation.

Читайте также:  Как вызвать настройки андроида при включении

Sample Proguard Fle:

5) Encryption of Local Storage through KeyStore

The Android Keystore system lets you store cryptographic keys in a container to make it more difficult to extract from the device. Once keys are in the keystore, they can be used for cryptographic operations with the key material remaining non-exportable. Moreover, it offers facilities to restrict when and how keys can be used, such as requiring user authentication for key use or restricting keys to be used only in certain cryptographic modes.

6) No use of implicit broadcast/ Use of LocalBroadcastManager

With apps targeting Android O, all implicit BroadcastReceivers registered in the manifest (except these) will stop working.

Use LocalBroadcastManager to register for and send broadcasts of Intents to local objects within your process. This has a number of advantages over sending global broadcasts with sendBroadcast(Intent):

You know that the data you are broadcasting won’t leave your app, so don’t need to worry about leaking private data.

It is not possible for other applications to send these broadcasts to your app, so you don’t need to worry about having security holes they can exploit.

It is more efficient than sending a global broadcast through the system.

To protect broadcast, it needs to be registered with permissions when it is declare.

Never trust the data that is being sent with it. It’s passing through a trust zone to arrive in the app, so it needs to be validated

7) MediaProjection: ( Screenshots and screen protecting)

Protect all sensitive windows within the App by enabling the FLAG_SECURE flag. This flag will prevent Apps from being able to record the protected windows. Also, the flag will prevent users from taking screenshots of these windows (by pressing the VOLUME_DOWN and POWER buttons). See for more details

8) Android Component Hijacking via Intent

Android components ( Activity, Broadcast Receiver, Content Provider, Service App) have their own entry points and can be activated individually. These components can be exposed to other apps for flexible code and data sharing.

Android (mainly) uses Manifest XML file to define component exposure. Intentscome into play here because they are the main mechanism for communication between components. Intents are used to start activities and services, bind to services, and convey notifications to broadcast receivers. By default, a component can only receive intents from other components in the same application, but it can be configured to accept intents from outside applications by setting the android:exported attribute in the manifest. An intent can be classified as one of two types based on how it is addressed.

There are two main ways that the security of intents can be compromised:

Android framework provides «PendingIntent» mechanism to safely perform the actions of an intent given by untrusted apps. In some situations, it can be a good measure for this kind of vulnerabilities.

9) No Encryption Under Https

HTTPS avoids the eavesdropping of application traffic but internal malicious users can use specialized software to view the traffic under the layer of https and may exploit any vulnerabilities present in clear text communication under https so it is not recommended to transmit clear text under https.

10) Add Custom Permissions to protect Android Components

Android components (Activity, Services, Broadcast Receivers, Content Provided) should defined permissions to restrict who can start the associated components. The permission is checked when the component is going to start. If the caller does not have the required permission then security exception is thrown for that call.

11) Disable Stacktrace in Release Mode

Stack trace will show the full trace right into the core, and will reveal details about what technologies you’re using, and possible versions as well. This gives intruders valuable info on possible weaknesses that could be exploited. A stack trace can reveal

12) Android 10 Security Features (API Level 29)

Updating Android Target Sdk to Android 10 (API Level 29) will automatically make your app secure as some level as it introduces a number of features and behavior changes to better protect users’ privacy.

Current encryption standards require devices have cryptographic acceleration hardware. Because of this requirement many devices are not capable of using storage encryption. Android 10 launch Adiantum which is designed to run efficiently without specialized hardware, and can work across everything from smart watches to internet-connected medical devices. Moreover, it has added TLS 1.3 support by default. TLS 1.3 is faster, more secure, and more private.

The underlying framework is updated with robust support for face and fingerprint authentication. The user must perform an action to proceed, such as tap their finger to the fingerprint sensor. If they’re using face or iris to authenticate, then the user must click an additional button to proceed. The explicit flow should be used for all high-value transactions such as payments.

Restrictions on starting activities from the background

Android 10 (API level 29) and higher place restrictions on when apps can start activities when the app is running in the background. These restrictions help minimize interruptions for the user and keep the user more in control of what’s shown on their screen.

Licensed under the Apache License, Version 2.0 (the «License»); you may not use this file except in compliance with the License. You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an «AS IS» BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Источник

Оцените статью