android应用安全
In order to preserve user trust and maintain data integrity, developing secure mobile application is one of the major challenge for most of the mobile app developers. This article will take you through some of the best practices that should be followed while building Android app to avoid security vulnerabilities.
为了保持用户信任并保持数据完整性,开发安全的移动应用程序是大多数移动应用程序开发人员面临的主要挑战之一。 本文将带您了解构建Android应用程序以避免安全漏洞时应遵循的一些最佳做法。
1.与其他应用程序保持安全通信 (1. Maintain Secure communication with other apps)
A. Use implicit intents to show app chooser that provides option to user to launch at least two possible apps on the device for the requested action. This allows users to transfer sensitive information to the app that they trust.
A.使用隐式意图来显示应用选择器,该选择器向用户提供选项以为请求的操作在设备上启动至少两个可能的应用。 这允许用户将敏感信息传输到他们信任的应用程序。

B. Apply signature-based permissions while sharing data between two apps that is controlled by you. These permissions do not need user confirmation, but instead it checks that the apps accessing the data are signed using the same signing key. Hence offer more streamlined and secure user experience.
B.在您控制的两个应用程序之间共享数据时,应用基于签名的权限 。 这些权限不需要用户确认,而是检查是否使用相同的签名密钥对访问数据的应用程序进行了签名。 因此,提供了更加简化和安全的用户体验。
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<permission android:name="my_custom_permission_name"android:protectionLevel="signature" />
C. Non-exported content providers — Unless you intend to send data from your app to other apps, explicitly disallow other apps to access your ContentProvider in manifest using android:exported=”false”(by default it is “true” for Android version lower than 4.4 ).
C. 非导出内容提供商 -除非您打算将数据从您的应用程序发送到其他应用程序,否则使用android:exported =“ false”明确禁止其他应用程序访问清单中的ContentProvider (对于Android版本,默认情况下为“ true”低于4.4)。
2.安全的网络通信 (2. Secure Network communication)
Ensure network security with Security with HTTPS and SSL — For any kind of network communication we must use HTTPS (instead of plain http) with proper certificate implementation. For details please refer here.
通过具有HTTPS和SSL的安全性来确保网络安全性-对于任何类型的网络通信,我们都必须使用HTTPS(而不是纯http)以及适当的证书实现。 有关详细信息,请参阅此处 。
Secure connection with server can be established in following ways:
可以通过以下方式建立与服务器的安全连接:
A. Communication with web server having well-known trusted CA certificate does need any additional steps to take while creating the http request.
A.与具有众所周知的受信任CA证书的 Web服务器的通信在创建http请求时确实需要采取任何其他步骤。
val url = URL("https://www.google.com")
val urlConnection = url.openConnection() as HttpsURLConnection
urlConnection.connect()
urlConnection.inputStream.use {
...
}
B. By adding a network security configuration: If your app uses new or custom CAs, you can declare your network’s security settings in a configuration file. This process allows you to create the configuration without modifying any app code.
B.通过添加网络安全配置:如果您的应用使用新的或自定义的CA,则可以在配置文件中声明网络的安全设置。 此过程使您无需修改任何应用程序代码即可创建配置。
To add a network security configuration file to your app, follow these steps:
要将网络安全配置文件添加到您的应用程序,请按照下列步骤操作:
i) Declare the configuration in your app’s manifest:
i)在您的应用清单中声明配置:
<manifest ... >
<applicationandroid:networkSecurityConfig="@xml/network_security_config"
... >
<!-- Place child elements of <application> element here. -->
</application>
</manifest>
ii) Add an XML resource file, located at
res/xm/network_security_config.xml
.ii)添加一个XML资源文件,位于
res/xm/network_security_config.xml
。Specify that all traffic to particular domains should use HTTPS by disabling clear-text:
通过禁用明文,指定到特定域的所有流量都应使用HTTPS:
<network-security-config>
<domain-config cleartextTrafficPermitted="false">
<domain includeSubdomains="true">secure.example.com</domain>
...
</domain-config>
</network-security-config>
During the development process, you can use the
<debug-overrides>
element to expliticly allow user-installed certificates. This element overrides your app's security-critical options during debugging and testing without affecting the app's release configuration. The following snippet shows how to define this element in your app's network security configuration XML file:在开发过程中,可以使用
<debug-overrides>
元素明确允许用户安装证书。 在调试和测试期间,此元素将覆盖应用程序的安全关键选项,而不会影响应用程序的发行版配置。 以下代码段显示了如何在应用程序的网络安全配置XML文件中定义此元素:
<network-security-config>
<debug-overrides>
<trust-anchors><certificates src="user" />
</trust-anchors>
</debug-overrides>
</network-security-config>
C. Create your own trust manager If web server has a certificate signed by a new or custom CA which is not trusted by the mobile device and additionally you cannot use a network security configuration.
C.创建您自己的信任管理器如果Web服务器具有由新CA或自定义CA签名的证书,而该证书不受移动设备信任,并且您不能使用网络安全配置。
For this scenario, you may need to set up a trust manager and handle all SSL warnings that occurs .
对于这种情况,您可能需要设置信任管理器并处理发生的所有SSL警告。
D. Certificates Pinning :Application can be limited to accept only a set of certificates by either limiting the set of CAs they trust or by certificate pinning.
D. 证书固定 :通过限制它们信任的CA集合或通过证书固定,可以将应用程序限制为仅接受一组证书。
It is achieved by providing a set of certificates by hash of the public key (SubjectPublicKeyInfo
of the X.509 certificate). A certificate chain is then valid only if the certificate chain contains at least one of the pinned public keys.
它是通过按公钥的哈希(X.509证书的SubjectPublicKeyInfo
)提供一组证书来实现的。 只有当证书链包含至少一个固定的公钥时,证书链才有效。
Other scenarios : There are some other factors that should be considered when your application tries to access data through internet:
其他情况 :当您的应用程序尝试通过Internet访问数据时,还应考虑其他一些因素:
i. Use WebView objects carefully : The WebView
objects in your app shouldn't allow users to navigate to sites that are outside of your control.Additionally, JavaScript interface support should be enabled only if you completely control and trust the content in your app's WebView objects.
一世。 谨慎使用WebView对象:应用程序中的WebView
对象不应允许用户导航到控件之外的网站。此外,仅当您完全控制并信任应用程序的WebView对象中的内容时,才应启用JavaScript界面支持 。
Use HTML message channels instead of evaluateJavascript()
to communicate between a website and your app.Check the Android documentation to see how to secure your WebView.
使用HTML消息通道而不是validateJavascript evaluateJavascript()
在网站和您的应用之间进行通信。查看Android文档以了解如何保护WebView。
ii. Use High-Level Authentication : Authentication mechanisms plays a crucial role in the mobile application security. Sensitive information can be secured efficiently through multi factor authentication,a robust session management and a disconnected system. . It is also essential to set up advanced authorization with the support of tools such as OAuth 2.0 or JSON web tokens for added security of Android apps.
ii。 使用高级身份验证:身份验证机制在移动应用程序安全中起着至关重要的作用。 通过多因素身份验证,强大的会话管理和断开连接的系统,可以有效地保护敏感信息。 。 在OAuth 2.0或JSON Web令牌等工具的支持下设置高级授权也至关重要,以增强Android应用程序的安全性。
3.提供正确的权限 (3. Provide the right permissions)
App should request only the minimum number of permissions necessary to function properly.
应用应仅请求正常运行所需的最少数量的权限。
It should not add a permission to complete an action that could be completed in another app. Instead, use an intent to defer the request to a different app that already has the necessary permission.
它不应添加权限来完成可以在另一个应用程序中完成的操作。 而是使用意图将请求推迟到已经具有必要权限的其他应用程序。
For example, If an App requires to create a contact to a contact app,delegates the responsibility of creating the contact to a contacts app, which has already been granted the appropriate WRITE_CONTACTS permission.
例如,如果某个应用程序需要创建与某个联系人应用程序的联系人,则将创建该联系人的职责委托给已经获得了适当的WRITE_CONTACTS权限的联系人应用程序。
4.数据存储的安全性 (4. Security on data storage)
Cryptography is the most efficient way to achieve data security. Hence, Use appropriate Encryption mechanism while dealing with data inside app. To achieve greater key security, use the Android Keystore system. Please find a nice article on Encryption here.
密码术 是实现数据安全性的最有效方法。 因此,在处理应用程序内部的数据时,请使用适当的加密机制。 要实现更高的密钥安全性,请使用Android Keystore系统 。 请在此处找到有关加密的不错的文章。
Following describes the best practices for storing data in your device.
以下内容介绍了在设备中存储数据的最佳做法。
A.在内部存储中存储私有数据 (A. Storing private data within internal storage)
Store all private user data within the device’s internal storage, which is sandboxed per app. There is no need to request permission to access these files, and cannot be accessed by other apps. Whenever the user uninstalls an app, the device deletes all files that the app saved within internal storage.Consider working with EncryptedFile
objects, which are available from the Security library, instead of File
objects.Find the example here:
将所有私人用户数据存储在设备的内部存储中,该内部存储按应用沙盒存储。 无需请求访问这些文件的权限,其他应用也无法访问。 每当用户卸载应用程序时,设备都会删除该应用程序保存在内部存储中的所有文件,请考虑使用EncryptedFile
对象(可从安全性库中获得 )而不是File
对象,在此处查找示例:
B.谨慎使用外部存储 (B. Use external storage cautiously)
By default, the Android system doesn’t enforce security restrictions on data that resides within external storage, and the storage medium itself isn’t guaranteed to stay connected to the device. Therefore, apply the following security measures to provide safe access to information within external storage.
默认情况下,Android系统不对外部存储中的数据实施安全限制,并且不保证存储介质本身保持与设备的连接。 因此,请应用以下安全措施以提供对外部存储中信息的安全访问。
Use scoped directory access: If your app needs to access only a specific directory within the device’s external storage, use scoped directory access to limit your app’s access to a device’s external storage accordingly.
使用作用域目录访问:如果您的应用仅需要访问设备外部存储中的特定目录,请使用作用域目录访问来相应地限制您的应用对设备外部存储的访问。
Access app-specific files: If a file doesn’t contain private or sensitive information but provides value to the user only in your app, store the file in an app-specific directory on external storage.
访问特定于应用程序的文件:如果文件不包含私人或敏感信息,但仅在您的应用程序中为用户提供价值,请将文件存储在外部存储设备上特定于应用程序的目录中 。
C.仅将非敏感数据存储在缓存文件中 (C. Store only non-sensitive data in cache files)
To provide quicker access to non-sensitive app data, store it in the device’s cache. For caches larger than 1 MB in size, use getExternalCacheDir()
; otherwise, use getCacheDir()
. Each method provides you with the File
object that contains your app's cached data.
要提供对非敏感应用程序数据的更快访问,请将其存储在设备的缓存中。 对于大于1 MB的缓存,请使用getExternalCacheDir()
; 否则,请使用getCacheDir()
。 每种方法都为您提供File
对象,其中包含应用程序的缓存数据。
D.在私有模式下使用SharedPreferences (D. Use SharedPreferences in private mode)
To create or access your your app’s SharedPreferences
objects using getSharedPreferences()
, use MODE_PRIVATE
so that your app can access the information within the shared preferences file.
要使用getSharedPreferences()
创建或访问应用程序的SharedPreferences
对象,请使用MODE_PRIVATE
以便您的应用程序可以访问共享首选项文件中的信息。
Moreover, EncryptedSharedPreferences
should be used for more security which wraps the sharedpreferences class and automatically encrypts keys and values.
此外,应使用EncryptedSharedPreferences
以获得更高的安全性,该安全性包装了sharedpreferences类并自动加密了密钥和值。
5.保持依赖关系和库为最新,以使这些通信点更安全。 (5. Keep dependencies and libraries up-to-date to make these points of communication more secure.)
6.使用R8编译器缩小,混淆和优化代码 (6. Shrink, obfuscate, and optimize your code with the R8 compiler)
If you are building your project using Android Gradle plugin 3.4.0 or higher, the plugin no longer uses ProGuard to perform compile-time code optimization. Instead, the plugin works with the R8 compiler to handle the following compile-time tasks:
如果您使用Android Gradle插件3.4.0或更高版本构建项目,则该插件将不再使用ProGuard来执行编译时代码优化。 而是,该插件与R8编译器一起使用以处理以下编译时任务:
Code shrinking (or tree-shaking): detects and safely removes unused classes, fields, methods, and attributes from your app and its library dependencies (making it a valuable tool for working around the 64k reference limit).
代码收缩(或摇树):从应用程序及其库依赖项中检测并安全删除未使用的类,字段,方法和属性(使其成为解决64k参考限制的有价值的工具)。
Resource shrinking: removes unused resources from your packaged app, including unused resources in your app’s library dependencies.
资源缩减:从打包的应用程序中删除未使用的资源,包括应用程序库依赖项中的未使用资源。
Obfuscation: shortens the name of classes and members, which results in reduced DEX file sizes.
混淆:缩短类和成员的名称,从而减小DEX文件的大小。
Optimization: inspects and rewrites your code to further reduce the size of your app’s DEX files.
优化:检查并重写代码以进一步减小应用程序DEX文件的大小。

结论: (Conclusion:)
These are the best practices that every mobile app developer must follow to secure the app from vulnerability. This helps you in developing highly secure apps required to prevent valuable user information of your app and maintain trust of your client.
这些是每个移动应用程序开发人员都必须遵循的最佳做法,以保护应用程序免受漏洞侵害。 这可以帮助您开发高度安全的应用程序,以阻止应用程序的宝贵用户信息并维护客户的信任。
Thanks for reading this article. Please Clap, Follow and comments to motivate me for posting more articles in the days to come.
感谢您阅读本文。 请拍手 , 关注 并 发表评论 激励我在以后的日子里发布更多文章。
Please have a look into my previous articles on Memory Leak in Android.
请查看我以前有关Android中的Memory Leak的文章。
参考书目: (Bibliography:)
https://developer.android.com/topic/security/datahttps://developer.android.com/training/articles/security-tips https://developer.android.com/training/articles/security-sslhttps://proandroiddev.com/secure-data-in-android-encryption-7eda33e68f58
https://developer.android.com/topic/security/data https://developer.android.com/training/articles/security-tips https://developer.android.com/training/articles/security-ssl https ://proandroiddev.com/secure-data-in-android-encryption-7eda33e68f58
翻译自: https://medium.com/@amritlalsahu5/how-to-develop-a-secure-android-app-b4ec103ece8c
android应用安全