-->

BroadcastReceiver permission for adb shell

2020-08-09 10:40发布

问题:

Consider a simple tool using a BroadcastReceiver to achieve a simple goal. Because this should not be used by other applications, it defines a permission with a protectionLevel of signature or signatureOrSystem:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="any.test">

    <permission
        android:name="any.test.PERMISSION"
        android:protectionLevel="signatureOrSystem" />

    <application android:label="AnyTest">
        <receiver
            android:name=".Receiver"
            android:exported="true"
            android:permission="any.test.PERMISSION" />
    </application>
</manifest>

Now I'd like to test this by sending broadcasts via

adb shell am broadcast -n any.test/.Receiver

from my computer. While this works perfectly fine on an emulator, it doesn't work at all on a real device when this permission is set. If the permission is not set, everything works as intended.

So how can I define or grant the permission so that I can test all this on a real device with ADB?

I want to make this exported receiver a little more secure in debug mode, so if there's a special permission for ADB usage or a run-time test to only allow calls from ADB I can implement in Receiver.onReceive(Context, Intent), it would help too. The receiver doesn't have to work for ADB and other apps at the same time.

回答1:

A root shell can send any broadcast protected by any permissions.
A normal shell also has been granted lots of permissions, check this file in the AOSP souce code: frameworks\base\packages\Shell\AndroidManifest.xml.

Replace your any.test.PERMISSION with one permission in this file that the protectionLevel is signatureOrSystem, like android.permission.REAL_GET_TASKS. After that, you can send broadcast to this receiver in shell, but other 3rd app can not.