组件通信安全(Intent)

这里主要涉及到了Activity、Content Provider、Service、Broadcast Receiver等。这些如果在Androidmanifest.xml配置不当,会被其他应用调用,引起风险。android应用内部的Activity、Service、Broadcast Receiver等,他们通过Intent通信,组件间需要通信就需要在Androidmanifest.xml文件中暴露组件,前面提到的风险就有可能是不恰当的组件暴露引起的。

一、Intent基础知识

Intent启动不同组件的方法如下:         

组件名称 方法名称
Activity startActivity() startActivityForResult()
Service startService() bindService()
Broadcasts sendBroadcast() sendOrderedBroadcast()

sendStickyBroadcast() |

     Intent的两种基本用法:一种是显式的Intent,即在构造Intent对象时就指定接收者;

另一种是隐式的Intent,即Intent的发送者在构造Intent对象时,并不知道也不关心接收

者是谁,有利于降低发送者和接收者之间的耦合。

显示调用例子:

Intent intent =  new  Intent();
intent.setClassName( "com.samples.intent.simple" , 
                     "com.samples.intent.simple.TestActivity" );
startActivity(intent);

Intent intent =  new  Intent(A.activity,B.class);
startActivity(intent);

隐式调用例子

Intent intent =  new  Intent(Intent. ACTION_DIAL );
startActivity(intent);
Intent intent =  new  Intent("com.test.broadcast");
intent.putString("PASSWORD","123456"); 
sendBroadcast(intent);
Intent intent =  new  Intent("com.test.service");
intent.putString("USERNAME","test"); 
startService(intent);

 显示调用和隐式调用都能过在不同应用间传递数据。

二、可能产生的风险:

1、恶意调用

2、恶意接受数据

3、仿冒应用,例如(恶意钓鱼,启动登录界面)

4、恶意发送广播、启动应用服务。

5、调用组件,接受组件返回的数据

6、拦截有序广播

上面也是想到了一部分,应用中应该会有更多的例子。

三、怎样避归风险:

1、最小化组件暴露

不参与跨应用调用的组件添加android:exported="false"属性,这个属性说明它是私有的,只有同一个应用程序的组件或带有相同用户ID的应用程序才能启动或绑定该服务。

  <activity
            android:name=".LoginActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait" 
            android:exported="false">

2、设置组件访问权限

参与跨应用调用的组件或者公开的广播、服务设置权限。设置权限如下:

(1)组件添加android:permission属性。

<activity android:name=".Another" android:label="@string/app_name"
           android:permission="com.test.custempermission">
</activity>

(2)声明属性

<permission android:description="test"  
        android:label="test"  
        android:name="com.test.custempermission"  
        android:protectionLevel="normal">  
    </permission>

protectionLevel有四种级别normal、dangerous、signature、signatureOrSystem。signature、signatureOrSystem时,只有相同签名时才能调用。

(3)调用组件者声明

<uses-permission android:name="com.test.custempermission" />

3、暴露组件的代码检查

Android 提供各种 API 来在运行时检查、执行、授予和撤销权限。这些 API

是 android.content.Context 类的一部分,这个类提供有关应用程序环境的全局信息。

if (context.checkCallingOrSelfPermission("com.test.custempermission")
        != PackageManager.PERMISSION_GRANTED) {
            // The Application requires permission to access the  
            // Internet");
} else {
    // OK to access the Internet
}
文章导航