Binders and Window Tokens (Window token)

Source: Internet
Author: User

Binders and Window Tokens (Window token)
Original article address: workshop? Simply put, how does the core system service of Android respond to requests of third-party applications efficiently and securely?
Unexpectedly, the answer to all these questions is exceptionally simple: YesBinder. Binders is the cornerstone of the Android system architecture. They abstract many details of the underlying IPC for developers, enabling the program to easily talk to system services or other remote service components. in addition, the Binder has many other cool functions, so it is widely used in the system and runs through the entire system, so that the underlying framework can solve security problems. this article will explain in detail one of these features, Binder token (tokens ).
The Tokens Binder has an interesting attribute: no matter how many processes are crossed, each instance maintains only one unique ID throughout the system. this is a 32-bit int value allocated by the Binder kernel driver after analyzing the transaction of each Binder. to ensure that the "=" Operation in Java applies to the uniqueness and cross-process Object Identity conventions of the Binder, the reference judgment of the Binder object is somewhat different from that of other objects. to be precise, each Binder object reference is allocated by one of the following two: the virtual memory address pointing to a Binder object in the same process, or a unique 32-bit handle (allocated by the Binder kernel driver) points to the virtual memory address of the Binder in different processes. in the Binder kernel driver, a Map of the local address and remote Binder handle is maintained for each Binder (and vice versa), and a suitable value is assigned to each Binder object reference, make sure that they can also work as expected in remote processes. the unique object ID rules of the Binder give them a special purpose: sharing, secure access token (Shared, security access token) (The document clearly shows that the Binder can be used like this "you can simply instantiate an original Binder object for cross-process sharing "). binders are globally unique, which means that you generate one, and no one else can generate the same one. therefore, the system's frameword widely uses the Binder token to ensure the security of cross-process interaction: a client can create a Binder object to share the token with the service process, in addition, the server can use it to verify that requests from the client are excluded from all forged requests.
Let's take a simple example to see how it works. If a program sends a request to PowerManager to obtain the screen lock (which will be released later ):

/** * An example activity that acquires a wake lock in onCreate()  * and releases it in onDestroy(). */public class MyActivity extends Activity {  private PowerManager.WakeLock wakeLock;  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");    wakeLock.acquire();  }  @Override  protected void onDestroy() {    super.onDestroy();    wakeLock.release();  }}

Reading the PowerManager source code helps us understand what is happening at the underlying layer (the source code is simplified ):
/** * The interface that applications use to talk to the global power manager * system service. * * @see frameworks/base/core/java/android/os/PowerManager.java */public final class PowerManager {  // Our handle on the global power manager service.  private final IPowerManager mService;  public WakeLock newWakeLock(int levelAndFlags, String tag) {    return new WakeLock(levelAndFlags, tag);  }  public final class WakeLock {    private final IBinder mToken;    private final int mFlags;    private final String mTag;    WakeLock(int flags, String tag) {      // Create a token that uniquely identifies this wake lock.      mToken = new Binder();      mFlags = flags;      mTag = tag;    }    public void acquire() {      // Send the power manager service a request to acquire a wake      // lock for the application. Include the token as part of the       // request so that the power manager service can validate the      // application's identity when it requests to release the wake      // lock later on.      mService.acquireWakeLock(mToken, mFlags, mTag);    }    public void release() {      // Send the power manager service a request to release the      // wake lock associated with 'mToken'.      mService.releaseWakeLock(mToken);    }  }}

What happened? Read the code step by step: the client requests an instance of the PowerManager class in onCreate. the PowerManager class provides a global PowerManagerService dialog interface for the client program to be in charge of the Power status of the device (such as determining the screen brightness and checking whether the device is inserted into the dock) in the system service process. the client creates and obtains a wake-up lock in onCreate ). powerManager sends a unique Binder token created by WakeLock as the parameter of the acquire () request. when PowerManagerService receives the request, it saves the received token security and forces the device to stay awake... the customer program released the wake-up lock in onDestroy. powerManager sends the unique Binder token created by WakeLock as the request parameter. when PowerManagerService receives the request, it compares the token with all the tokens it saves. If the same token is found, the wake-up lock is released. this extra "validation step" is an important security measure to prevent PowerManagerService from being cheated by other applications and releasing the wake-up lock. because of their object uniqueness, the Binder token is widely used in the system (select a file frameworks/base/services/java/com/android/server at will, it can be found that it uses several forms of Binder token. another cool example involves the status bar, notification management, and system UI. specifically, StatusBarManagerService maintains a global Binder token to the Map of the notification. when icationicationmanagerservice sends a request to add a notification to the status bar manager, the status bar manager generates a unique Binder token and transmits it to the notification manager and system UI at the same time. in this way, the third party will know the Binder token of the notification, and any changes to the notification (for example, the notification manager cancels a notification or the system UI detects that the user switches out a notification) will first pass the status manager. this makes the three system services easier to synchronize: the status bar manager can centrally control all the currently displayed notifications without interacting with the system UI and notification manager .) for security assurance. perhaps the most interesting example in all frameworks is the window token. Next we will discuss it.
If you have read the official document about the View class, you may be confused that the getWindowToken () method does not know its meaning. as the name implies, a window token is a special Binder token, which uniquely identifies a window in the system. window tokens are important for security because they prevent malicious programs from appearing on other program interfaces. the Window Manager requires the application to pass their window tokens as parameters for adding or deleting a window (with android. permission. SYSTEM_ALERT_WINDOW permission program, that is, "Draw on other program interfaces" permission, this rule is an exception. facebook Messenger and DicePlayer are two commonly used programs that require this permission, and they are used to add a window on the Interface of other programs in the background service ). if the token does not match, the window manager rejects the request and throws a BadTokenException. If the window token does not exist, the necessary identity suggestion steps cannot be implemented, and the window manager cannot prevent malicious programs.
Through this, you may want to know when a window token is required in actual development. Here are several examples:
When an application is started for the first time, ActivityMangerService (a global system service running in the system service process) is responsible for starting and managing new components, such as Activities and Services, at the same time, it also involves maintaining OOM adjustments and is used for processing, permissions, and task management when the kernel is low in memory.) a special window token is called Application Window token( Application window token), Which uniquely identifies the window of the application's top-layer container (you can obtain a reference by calling getApplicationWindowToken ). the Activity manager sends the token to the application and window manager at the same time, and each time the application wants to add a window, it passes the token to the window manager. this ensures secure interaction between the application and the window manager (because it makes it impossible for other programs to add a window to the top layer), and also makes it easier for the Activity manager to directly send requests to the window manager. for example, the Activity manager can say, "hide all windows of this token", and then the window manager can correctly select the window to close. developers who implement their own custom desktop programs (Launchers) can interact with the dynamic wallpaper window by calling sendWallpaperCommand (IBinder windowToken, String action, int x, int y, int z, Bundle extras) make it directly behind. to ensure Division No other applications on the desktop can interact with the dynamic wallpaper. The framework requires the developer to input a window token as the first parameter of this method. if the window token does not match the window of the current Activity located in front of the wallpaper, this command will be ignored and a warning will be printed. the application can request InputMethodManager to hide the keyboard by calling the hideSoftInputFromWindow (IBinder windowToken, int flags) method, but a window token must be provided as a parameter. If the token does not match the window token currently accepted, inputMethodManager rejects the request, which ensures that the malicious program cannot forcibly close the soft keyboard opened by other programs. manually add new windows to applications on the screen (for example, use addView (View, WindowManager. layoutParams) method) You may need to set WindowManager. layoutParams. token attribute to specify the window password of their application Card. generally, normal programs do not like this because the WindowManager object returned when getWindowManager () method is used has automatically set the token value for you. in other words, if you need to add a window to the screen from the background service in the future, you need to know that you should manually set the window token of your program to succeed. summary although their existence is blocked by most developers, the Binder token is widely used in the system for security. android is a large-scale distributed collaboration system that relies on the Binder object to be unique in all processes on the entire device. The Binder token is the driving force behind the collaboration of the entire framework. Without them, it will be difficult for the entire system to operate without secure interaction between application processes.

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.