Best practices-android program Security

Source: Internet
Author: User

Self-articles are mainly translated articles on the official website, and I have also added my own understanding. If there is any inaccuracy, please correct me.
Http://developer.android.com/guide/practices/security.html

Some virtual machines run within a security boundary and are isolated from their operating system programs, such as Java virtual machines and. net runtime environments.
On android, Dalvik virtual machines do not have such security boundaries. The application sandbox is implemented at the operating system level. Therefore
In the same program, Dalvik interacts with native code without any security boundaries.

Idle storage policy for mobile devices. Under normal circumstances, developers want to create modular applications and implement them through dynamic class loading. For this
There are two issues to consider: Program Logic and storage location. Do not use class resources that are not checked, such as insecure network resources or external storage.
Resources on the device, because such resources can be modified and include malicious actions.

Use native code

Generally, we recommend that developers use android sdk to develop most programs, rather than native code. The program uses native code
The build will be more complex and huge, and there may be some common memory usage errors, such as buffer exceptions.

Android is built on the Linux kernel. If you are familiar with Linux development, it is better to use native code. This document only takes a small amount of space.
Introduction to this recent practice, to learn more about the resources for LInux and Unix programming security, please visit this Web site http://www.dwheeler.com/secure-programs

An important difference between android and most other Linux operating environments is the program sandbox. On android, all programs run in the sandbox, even if the program contains
Native code. Developers familiar with Linux know that each program is assigned a unique UID and limited permissions. Of course, even if you are not familiar with Linux, you must understand this.
If you use native code, you need to be familiar with the content of program permissions. Http://source.android.com/tech/security/index.html

Store Data
Use internal program storage
By default, files created in the program can only be used by the program. Security storage for most programs is sufficient.

It is not recommended to use global read or write permissions between processes. In this way, some specific programs cannot be restricted to access data, and the data format cannot be controlled.
To do this, you can use ContentProvider to allow read and write data in the same way. You can also dynamically grant data access permissions as needed.

To provide more protection for sensitive data, some programs choose to encrypt local files using keys. For example, if the key is stored in the keystore
To protect users' passwords, instead of directly storing them on the device. However, in this case, data cannot be protected: the device is root, and the password entered by the user
Can be monitored. This can protect the loss of devices with file encryption systems.

Use External Storage

Global read/write permissions when files are stored on an external storage device, such as the SD card. Because external storage devices can be removed by users and can be modified by any program,
Do not store sensitive data on external storage devices.

For data obtained from any untrusted source, the program should check the input obtained from external storage. We strongly recommend that you do not use external storage devices.
Stores Dynamically Loaded executable files or class files. If the program loads executable files from external storage, the files must be signed and encrypted and checked before loading.

Use content providers

ContentProvider provides a storage mechanism, which can restrict your programs or provide an access portal for other programs. By default,
A ContentProvider is the portal provided to users by other programs. If you do not want other programs to access your ContentProvider
Android: exported = false.

Creating a ContentProvider opens an entry for other programs. You can specify a read/write permission or separate the read/write permissions. Suggestions
You separate the permissions and assign them as needed. Remember, it is usually easier to add permissions for new features in the future, instead of removing them, and affecting existing users.

If ContentProvider is used to share data between two programs developed by the same developer, it is preferred to use signature-level permissions. Signature permissions do not need to be confirmed by the user,
Therefore, it provides a better user experience and more access control over ContentProvider.

ContentProvider also provides more counter-question declarations, which are specified through the grantUriPermison element and use FLAG_GRANT_READ_URI_PERMISSION and FLAG_GRANT_WRITE_URI_PERMISSION
These flags are on the Intent object. The permission range can be further restricted by the grant-uri-permisstion element.

When you access ContentProvider, using methods with parameters, such as query (), update (), and delete () can prevent potential SQL Injection risks of untrusted data.
Note that it is not safe to use parameterized methods if assembled data is submitted to these methods.

Do not have such an incorrect opinion on write permissions. You can imagine that write permissions allow the use of SQL statements so that some data can be assembled using where clauses.
For example, an attacker may modify a row of data in call-log to view an existing phone number.
If the content provider has a predictable structure, the write permission is equivalent to both read and write permissions.

Using Interprocess Communication (IPC)
Use inter-process communication

Some android programs attempt to use traditional Linux inter-process communication technologies, such as network sockets and shared files. We strongly recommend that you use the android process.
Communication technology is not as good as intent, binder, service, and javaser. Android IPC Mechanisms allow you to verify that the program connects to your IPC program is valid.
Set security policies for IPC.

Many security components share data through the IPC Mechanism. Broadcast receivers, activities, and services are declared in the manifest of the program. If your IPC Mechanism doesn't want
For other programs to access, set the property of Android: exported to false. This is very useful. for multiple processes of multiple programs, use the same uid, or
Later, you decided not to share data through IPC, and you do not need to rewrite the code.

If your IPC is intended for access by other programmers, you can set the permission flag as a security policy. If IPC is a program of the same developer,
The signature-level permission control should be used. The signature permission does not need to be confirmed by the user, so it will provide a better user experience and more IPC access control.

Intent filtering is easy to confuse. Note that intent filtering should not be considered safe. This component can be called directly without any
Confirm intent filtering. You should perform input verification to ensure that your intent receiver receives the correct format sent by the receiver, service, and activity.
 
Using intents

The intent is the asynchronous IPC Mechanism recommended in Android. Based on your program requirements, you can use sendbroadcaset (), sendorderedbraodcast () or
Send intent directly to the specified program component.

Note that ordered broadcast can be consumed by all receivers and may not be sent to all programs. If you want to send an intent message to a specified receiver, the intent must be sent directly.
To the specified receiver.

If no intent has been specified, it may be received by other recipients. Only the recipient with the specified permission can receive the intent. You can set the intent permission.
Improve security.

Use the binder and AIDL Interfaces
Binder is a recommendation mechanism for android to remotely call IPC.

We strongly encourage designing interfaces in a manner that does not require interface specific
Permission checks. Binders are not declared within the application manifest, and therefore you
Cannot apply declarative permissions directly to a Binder. Binders generally inherit permissions
Declared in the application manifest for the Service or Activity within which they are implemented.
If you are creating an interface that requires authentication and/or access controls on a specific
Binder interface, those controls must be explicitly added as code in the interface.

If providing an interface that does require access controls, use checkCallingPermission ()
To verify whether the caller of the Binder has a required permission. This is especially
Important before accessing a Service on behalf of the caller, as the identify of your
Application is passed to other interfaces. If invoking an interface provided by a Service,
The bindService () invocation may fail if you do not have permission to access the given Service.
If calling an interface provided locally by your own application, it may be useful to use
ClearCallingIdentity () to satisfy internal security checks.

Use an IP Address:
We recommend that you use an Https network. Do not use any other insecure network. When using public wiff hotspots, these open networks are not
Encrypted network.

Use telephone networks:
The technology of sms is designed for communication between people, so it is not suitable for some programs. We recommend that you use C2DM and the IP network to send data to the device.
In the process of network transmission, sms does not encrypt data and has no strong verification mechanism. In particular, any sms recipient can receive messages from malicious users to your program,
Do not use unauthenticated sms to execute sensitive commands. It is also recognized that sms may be intercepted or spoofed through sms. Android devices
SMS messages are sent in the form of broadcast intent. Therefore, messages may be intercepted and read by programs that have the permission to read SMS messages.

Dynamic code Loading

We strongly do not recommend the apk program not to dynamically load code from the outside. If this is done, it will increase the risk of code injection and code tampering.
It also affects Version Control Box program testing. Finally, it will lead to poor verification of program behavior, so in some cases the program will be blocked.

If your program performs dynamic code loading, remember that the apk of the Dynamically Loaded code must have the same security permissions as the loader. Determined by the user
The installation of your program is based on unified labeling authentication.

The biggest security risk of dynamic code loading is the verification code source. If the program module is directly included in your apk, other programs cannot be modified. Whether it is the native library or loaded through DexClassLoader
This is true for all code. We have encountered a lot of programs trying to load insecure location code, such as downloading code from the network without security protocol encryption, or thinking about external storage.
Code is loaded at a location with the global write permission. These locations allow some people to modify the data content during network transmission, or install programs on the device to modify the data content.

Use WebView

Because the WebView component can parse HTML, Javascript, and other webpage content, it may encounter some common security problems, such as cross-site scripting (cross-site-scripting, javascript injection ).
Android contains a large number of security mechanisms to reduce this cross-domain Condemnation Problem, such as by limiting WebView to use the least feature.

If WebView in your program does not directly use Javascript, do not call setJavaScriptEnabled (). By default, WebView does not execute cross-site scripts.
Javascript execution.

Pay special attention to addJavaScriptInterface (), because it allows javascript to call android code to execute the program.
Only open addJavaScriptInterface () to trusted input sources. Otherwise, untrusted javascript may call android functions.
Generally, we recommend that you only open the addJavaScriptInterface () entry to the javascript in this program.

Do not trust the data downloaded over http. Use Https instead. If you only access a single website, even if it is trusted and controllable, HTTP may be attacked in the intermediate process,
Data is intercepted during transmission. Be cautious when using addJavaScriptInterface (). Do not trust the unverified scripts downloaded over http.
Note: Even if https is used, addJavaScriptInterface () increases the possibility of program attacks, although the security settings of the server and the android device have all the trusted CAS.

If you are using the same WebView for sensitive access information, you should delete any cached files stored locally by using the deleache () method. The small message header on the server can be used.
Signs like no-cache tell the program not to cache specific content.

Run input check

A common security problem is to directly run the input without performing adequate security checks. Android has a platform-level measure to reduce the problem of no input check exposed to the program,
You should try to use this feature wherever possible. At the same time, you must note that selecting a security language can reduce the input verification problem. We strongly recommend that you use the android SDK
Build your program.

If the native code obtained from files, networks, and IPC is used, potential security problems are also increased. Common problems are buffer overflow, user logout, and off-by-one errors. Android
Many technologies like ASLR and DEP are provided to reduce those errors during development, but they cannot solve these potential errors. Those technologies can be used to prevent pointer control and cache zone management problems.

Dynamic, string-based languages, such as javascript and SQL, can be input to check to prevent special characters and Script Injection problems.

If SQL database or content provider is used during data query, SQL injection may cause a problem. The final countermeasure is to use parameterized query, and you want
Some of them are the same. Limiting to read-only and write-only permissions can also reduce the potential risk of SQL injection.

If you use webview, you must consider the possibility of exaggerated script attacks (XSS. If your program and webview do not directly use JavaScript,
Do not call setjavascriptenabled (), so XSS will not happen. If the program must use JavaScript, consider other security measures
To prevent XSS attacks.

If you cannot use the preceding security features, we strongly recommend that you use a well-structured data format and fully verify the data format. At the same time, you must make a special character blacklist and replace the database with the character.
It will make a more effective policy. These technologies are very error-prone during use, so you must try to avoid errors.

Process User Data

In general, the most effective way is to use as few APIs as possible to access sensitive data and personal information. If the data is accessed, the data will not be stored or transmitted.
Finally, we consider using a hash or irreversible algorithm to process data. For example, if your program uses the hash algorithm to use the email hash value as the key, you must
Avoid storing and transmitting email addresses. This can prevent data from being exposed due to negligence, which can also reduce the chance of attacks on programs exposed to the outside.

If your program wants to access personal information such as user name and password, remember to use the privacy agreement to explain your use and storage information. Therefore,
In the following best security practices, we should minimize the amount of user data accessed.

You also need to consider whether your program will inadvertently expose personal information to other program parts, such as third-party ad components or third-party services used in your program.
If you do not know why these components or services require personal information, do not provide them to programs. Usually, reducing access to personal information can reduce the potential of the program
Security issues.

To access sensitive data, evaluate whether the data is transmitted to the server or on the client. Allow sensitive data to be used in client code
Prohibit user data transmission whenever possible.

At the same time, ensure that user data is not exposed to other programs through loose IPC, globally writable files, or the network. Here is a special case about repeated permissions.
.

It is necessary to create a unique global unique identifier to store a large number of IDs. Do not use phone numbers like phone numbers or IMEI because they are related to personal information.
More information about this topic is posted on the android developer blog. Http://android-developers.blogspot.com/2011/03/identifying-app-installations.html

Program developers need to pay special attention to the log information written on the device. on android, logs share resources and prevent the program from having the READ_LOGS permission.
Even if the mobile phone log is deleted temporarily or restarted, logs that record user information may leak user information to other programs.

Handling Credentials
Process credential
In general, we recommend that you obtain creden at the minimum frequency to reduce the success rate of phishing attacks. Instead, use the authorization token and refresh the token.

Do not store the user name and password on the device in any case.
Only the user name and password provided by the user are required for the first authentication, and the short activity period is used to specify the service authorization token.

If a service needs to access multiple programs, use AccountManager. If possible, use the AcctountMangaer class to call cloud services.
The password is stored on the device. Http://developer.android.com/reference/android/accounts/AccountManager.html

After using AccountManager to retrieve an Account, check the CREATOR before passing in any credentials,
So that you do not inadvertently pass credentials to the wrong application.
After using AccountManager to retrieve the account, check the creator before passing the creden. Do not pass the creden to the wrong program.

If your program is allowed to use the creden, use the checkSignature () method to sign the program when the program accesses AccounManager.
If there is only one program Access Credential, you can use KeyStore to store the credential information.

Using Cryptography
Use encryption technology

Data isolation is added to support full file system encryption and secure channel access. Android provides multiple array encryption algorithms to protect data.

In general, the use of an existing high-level framework can support most usage cases. If you need to securely retrieve files from a location, the simple Https URI is sufficient.
If you need a secure channel, consider using HttpsURLConnection or SSLSocket instead of writing your own protocol.

If you do find yourself needing to implement your own protocol, we stronugly recommend that you not implement your
Own cryptographic algorithms. Use existing cryptographic algorithms such as those in the implementation of AES or
RSA provided in the Cipher class.
If you need to implement your own protocol, we strongly recommend that you do not implement your own encryption algorithm. Use an existing encryption algorithm, such as AES or RSA, through the Cipher class.

Use a secure random number generator (SecureRandom) to initialize any Encrypted key (KeyGenerator). If the key is not a security-generated random number, the encryption strength is reduced,
It also allows offline attacks.

If you want to save the key for reuse, you can use a mechanism like KeyStore for long-term access through the encryption key.

Conclusion
Android provides developers with a variety of measures to design program security. These best practices ensure that your program can benefit from security.

You can receive more information on these topics and discuss security best practices
Other developers in the Android Security Discuss Google Group

You can see more Security topics or discussions in Android Security Discuss Google Group.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.