這里主要涉及到了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
}
~~~