Android Source Series < two > in-depth understanding from a security perspective broadcastreceiver (UP)

Source: Internet
Author: User

Mention Broadcastreceiver everyone is very familiar with it and Activity,service and ContentProvider and known as Android four components (four King Kong), visible broadcastreceiver the importance of Today we are mainly from a security perspective on the Broadcastreceiver called one of the four components. may have the child boots see here will have the question, Broadcastreceiver has what to say, is not first defines own broadcast receiver and then registers in the Manifest.xml file, calls the context in the place which needs to send the broadcast the Sendbroadcast () method or Sendorderbroadcast (), and finally do the corresponding logic in the OnReceive () method of our custom broadcast receiver? Well, the overall process of using broadcastreceiver is very OK, but also shows that you are very familiar with the use of broadcasting this piece, but today is from a security point of view to explain Broadcastreveiver, I believe you read this article will have some gains (*^__^ *) ......

The use of broadcastreceiver is very broad and simple, and its use can be summarized as three steps away:

    1. Define your own broadcastreceiver and implement the OnReceive () method
    2. Static registration in Androidmanifest.xml or dynamic registration in code
    3. Call the Sendbroadcast () method of the context to send the broadcast

Here first on the broadcast of two registration methods to do a description, broadcast registration is divided into dynamic registration and static registration of two ways. Static registration refers to a resident broadcast, whether or not our application is not running, as long as there are eligible broadcasts sent to our application can be accepted, dynamic registration refers to only when our application is running in order to accept the eligible broadcast. So when we want to use the radio to make a distinction: whether it is static or dynamic.

Following the above steps we define our own broadcast receiver Custombroadcastreceiver, define our own broadcast receivers need to inherit from the Broadcastreceiver class, which is the abstract type, so we need to implement OnReceive ( ) method, the code is as follows:

public class Custombroadcastreceiver extends Broadcastreceiver {public custombroadcastreceiver () {} @Overridepublic void OnReceive (Context context, Intent Intent) {log.e (This.getclass (). Getsimplename (), "Current time is:" + System.curre Nttimemillis ());}}
Our custom broadcast receivers are relatively simple and only print a single word in the OnReceive () method. Next we configure the Custombroadcastreceiver in the Androidmanifest.xml file, we let the receiver accept the broadcast of the specified action, the code is as follows:
<manifest xmlns:android= "http://schemas.android.com/apk/res/android" package= "Com.llew.seetao.a" Android:         Versioncode= "1" android:versionname= "1.0" > <uses-sdk android:minsdkversion= "8"/> <application        Android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name"                  Android:theme= "@style/apptheme" > <activity android:name= "com.llew.seetao.a.mainactivity" Android:label= "@string/app_name" > <intent-filter> <action android:name= "android.in Tent.action.MAIN "/> <category android:name=" Android.intent.category.LAUNCHER "/> </ intent-filter> </activity> <receiver android:name= "com.llew.seetao.a.custombroadcastrece            Iver "> <intent-filter> <action android:name=" Com.llew.seetao.customaction "/>   </intent-filter>     </receiver> </application></manifest> 
Well, after the Androidmanifest.xml file is configured with our broadcast receivers, we can send a broadcast. Add a button that responds to the event in the layout file Activity_main.xml first, with the following code:
<?xml version= "1.0" encoding= "Utf-8"? ><framelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android: background= "#aabbcc" >    <button        android:layout_width= "wrap_content"        android:layout_height= " Wrap_content "        android:onclick=" Sendbroadcast "        android:text=" test broadcast a program "/></framelayout>
In the layout file we use the OnClick property of the view (if you are not sure how to use the property), Mainactivity's code is as follows:
public class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);} public void Sendbroadcast (View v) {Intent Intent = new Intent (mainactivity.this, Custombroadcastreceiver.class); This.sendbroadcast (intent);}}
Once the above steps are complete, you can run the project, open the emulator or link the phone, run it, and the effect looks like this:

Click on the button and you will find a line of log output under Logcat, as shown in:

Here we can say that we have only mastered the use of broadcasting, if in the project we also use the broadcast in the same way, then your project may be at risk. Why do you say that, let's assume a scenario, if someone else decompile our APK package and see the broadcast in our config file, then he can send a broadcast in his app, because the broadcast we configured contains Intent-filter, so we can implicitly call this broadcast , will our apk react? In order to do this test, we create a new project B (referred to as Project A), as long as the B package name is not the same as a package name, so that the two projects can run on a device at the same time, so in the B project by implicitly send broadcast, the code is as follows:

public class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);} public void Sendbroadcast (View v) {Intent Intent = new Intent ("Com.llew.e.customaction"); This.sendbroadcast (Intent);}}
We run a run of the B program, click the button, by looking at the output of Logcat, oh,my God, if the log in Project A is printed out, as shown in:

From the Logcat printing results can be seen, we can actually send the broadcast through the implicit broadcasting receiver to respond, such an app if the release is indeed a security risk, there is no solution? The answer is yes, we'll look at 3 ways to solve this:

  1. To add an export property to a broadcast receiver
    <receiver android:name= "Com.llew.seetao.a.custombroadcastreceiver" android:exported= "false" >    < intent-filter>        <action android:name= "com.llew.seetao.customaction"/>    </intent-filter> </receiver>
    In the above code we just added the Export property when registering our Custombroadreceiver, and set the value of the property to False, is it OK to just add a property? There may be some children's boots still have doubts, in order to dispel the concerns of children's boots, we run the code, look at the results, the results are as follows:

    By running the LOGCAT output log under engineering A and Project B respectively, we can see that we have added the Export property to our custom receiver and it is really not possible to respond to our broadcast receivers in this way. So what's the nature of this property? There may be some child boots that have this kind of question, so let's take a look at how the official documentation explains the export attribute.

    English proficiency is limited, the official document is roughly translated:
    Whether the current broadcast sink can accept messages from an external application, if true, indicates that the message can be accepted from an external application, or false to indicate that the current broadcastreceiver can only receive broadcasts from the current app or from an app that has the same userid. The default value is determined by whether the current broadcastreceiver contains Intent-filter, and if there is no intent-filter, it can only be called by the class name, when the default value is False, if it contains Intent-filter , the default value is true. Not only does this attribute specify whether Broadcastreceiver is exposed to other users, you can also use permission to restrict external apps from sending messages to the current app's receiver.
    At the end of the official document, we can also add permissions to restrict external references to send messages to our receiver, and then we'll look at how permissions are used, in addition to using the export attribute.
  2. Add custom permissions to a broadcast receiver
    A) First, customize the permissions, the code is as follows:
    <permission android:name= "com.llew.seetao.permission.customaction" android:protectionlevel= "normal" ></ Permission>
    b) Second, add permission permission to receiver, the code is as follows:
    <receiver android:name= "Com.llew.seetao.a.custombroadcastreceiver" android:permission= " Com.llew.seetao.permission.customaction ">    <intent-filter>        <action android:name=" Com.llew.seetao.customaction "/>    </intent-filter></receiver>
    c) Run the code to see the results as follows:

    By observing that I did find a way to add custom permissions then the B program does not call up the broadcast in a program, hehe, and see here our happy little heart thump straight jump. If so, then you are wrong, because in a program we do add custom permissions to our custom broadcast, that is, the application can have that permission, if we also define the same permissions in the B program, then the result will be God horse appearance? We continue to do experiments to verify that this time we also put the B program to add the same permissions, and then use the permissions, the code is as follows:
    <manifest xmlns:android= "http://schemas.android.com/apk/res/android" package= "COM.LLEW.SEETAO.B" Android: Versioncode= "1" android:versionname= "1.0" > <uses-sdk android:minsdkversion= "8"/> <permission    Android:name= "Com.llew.seetao.permission.customaction" android:protectionlevel= "normal" ></permission> <uses-permission android:name= "com.llew.seetao.permission.customaction"/> <application Android:allo Wbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" Android:theme= "@ Style/apptheme "> <activity android:name=" com.llew.seetao.b.mainactivity "android:label=" @st Ring/app_name "> <intent-filter> <action android:name=" Android.intent.action.MAIN "/&                Gt <category android:name= "Android.intent.category.LAUNCHER"/> </intent-filter> </activity&    Gt </applicatiOn></manifest> 
    We then run the program in such a way and run it separately, and the results are as follows:

    Alas, fuck,b program can also be transferred to our radio, at this time you may have 10,000 grass mud horse in the Pentium, this broadcast also let people do not use, hehe, we this piece of article is from the security point of view to explain broadcastreceiver, there must be a countermeasure, Remember the permissions we defined in the a program? If you don't remember, the code looks like this:
    <permission android:name= "com.llew.seetao.permission.customaction" android:protectionlevel= "normal" ></ Permission>
    Define our own permissions when we give permission to use the level is normal, if you are not too understanding or property of the level of the relevant permission, you can go to the official website to view, here is no longer detailed, by looking at the official website, the permission level has a signature, In other words, if we set the permission level to signature when we customize the permissions, only the app with the same signature will be able to tune up our app, which is relatively secure, because we are sure to use our own signature when we make the version, and others generally can't get our signature. So this method is feasible. At this time you must be happy to open the flowers, it is magic high feet, do not worry, we have another more reliable and efficient solution, which is also my development has been used, please continue to read (*^__^*) ...
  3. Use the official recommended Localbroadcastmanager
    Localbroadcastmanager is in the Android V4 package (if you do not want to introduce the V4 package, you can copy the class directly from the source), it has the following advantages over the global broadcast:
    (1). Broadcast will only be sent within your app, no need to worry about data leakage, more security
    (2). Other apps cannot send broadcasts to your app without worrying about security vulnerabilities in your app
    (3). It does not need to be sent to the entire system, so it is more efficient than the global broadcast
    Well, say so much, let's hurry and see how this god-Localbroadcastmanager is going to work? or using the Custombroadcastreceiver defined above, in the OnReceive () method we only print the current time, the code is as follows:
    public class Custombroadcastreceiver extends Broadcastreceiver {public static final String local_custom_action = "Com.lle W.seetao.customaction ";p ublic custombroadcastreceiver () {} @Overridepublic void OnReceive (context context, Intent Intent) {LOG.E (This.getclass (). Getsimplename (), "Current time is:" + system.currenttimemillis ());}}
    Then let's look at the code in Mainactivity, as shown below:
    public class Mainactivity extends Activity {private Localbroadcastmanager mbroadcastmanager;private Custombroadcastreceiver mlocalreceiver; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (R.layout.activity_main); Registerbroadcastreceiver ();} private void Registerbroadcastreceiver () {Mbroadcastmanager = Localbroadcastmanager.getinstance (MainActivity.this); Mlocalreceiver = new Custombroadcastreceiver (); intentfilter filter = new Intentfilter (Custombroadcastreceiver.local_ custom_action); Mbroadcastmanager.registerreceiver (mlocalreceiver, filter);} public void Sendbroadcast (View v) {Intent Intent = new Intent (custombroadcastreceiver.local_custom_action); Mbroadcastmanager.sendbroadcast (intent);} @Overrideprotected void OnDestroy () {Super.ondestroy (); if (null! = Mbroadcastmanager) { Mbroadcastmanager.unregisterreceiver (Mlocalreceiver);}}}
    We instantiate the Mbroadcastmanager object in Mainactivity's OnCreate () method by Localbroadcastmanger.getinstance (). The register () method is then called by the Mbroadcastmanager object to register our broadcast receiver, and the last code to send the broadcast is called the Mbroadcastmanger Sendbroadcast () method, in OnDestroy () The method also calls the Mbroadcastmanager's Unregisterreceiver () method, we run the code, the result is as follows:

    By running the results, it is normal to use Localbroadcastmanager, so why is it safe and efficient to use this method? As this post is a bit long, in the next article I will analyze from the source point of view why the use of Localbroadcastmanager is safe and efficient, please look forward to ...



Android Source Series < two > in-depth understanding from a security perspective broadcastreceiver (UP)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.