Android 设备管理

Device Administration

In this document

  1. Device Administration API Overview
    1. How does it work?
    2. Policies
  2. Sample Application
  3. Developing a Device Administration Application
    1. Creating the manifest
    2. Implementing the code

Key classes

  1. DeviceAdminReceiver
  2. DevicePolicyManager
  3. DeviceAdminInfo

Android 2.2 introduces support for enterprise applications by offering theAndroid Device Administration API. The Device Administration API provides deviceadministration features at the system level. These APIs allow you to createsecurity-aware applications that are useful in enterprise settings, in which ITprofessionals require rich control over employee devices. For example, thebuilt-in Android Email application has leveraged the new APIs to improveExchange support. Through the Email application, Exchange administrators canenforce password policies — including alphanumeric passwords or numericPINs — across devices. Administrators can also remotely wipe (that is,restore factory defaults on) lost or stolen handsets. Exchange users can synctheir email and calendar data.

This document is intended for developers who want to develop enterprisesolutions for Android-powered devices. It discusses the various featuresprovided by the Device Administration API to provide stronger security foremployee devices that are powered by Android.

Device Administration API Overview

Here are examples of the types of applications that might use the Device Administration API:

  • Email clients.
  • Security applications that do remote wipe.
  • Device management services and applications.

How does it work?

You use the Device Administration API to write device admin applications that usersinstall on their devices. The device admin application enforces the desiredpolicies. Here's how it works:

  • A system administrator writes a device admin application that enforcesremote/local device security policies. These policies could be hard-coded intothe app, or the application could dynamically fetch policies from a third-partyserver.
  • The application is installed on users' devices. Android doesnot currently have an automated provisioning solution. Some of the ways a sysadmin mightdistribute the application to users are as follows:
    • Android Market.
    • Enabling non-market installation.
    • Distributing the application through other means, such as email or websites.
  • The system prompts the user to enable the device admin application. Howand when this happens depends on how the application is implemented.
  • Once users enable the device admin application, they are subject toits policies. Complying with those policies typically confers benefits, such asaccess to sensitive systems and data.

If users do not enable the device admin app, it remains on the device, but in an inactive state. Users will not be subject to its policies, and they will conversely not get any of the application's benefits—for example, they may not be able to sync data.

If a user fails to comply with the policies (for example, if a user sets apassword that violates the guidelines), it is up to the application to decidehow to handle this. However, typically this will result in the user not beingable to sync data.

If a device attempts to connect to a server that requires policies notsupported in the Device Administration API, the connection will notbe allowed. The Device Administration API does not currently allow partialprovisioning. In other words, if a device (for example, a legacy device) doesnot support all of the stated policies, there is no way to allow thedevice to connect.

If a device contains multiple enabled admin applications, the strictest policy isenforced. There is no way to target a particular adminapplication.

To uninstall an existing device admin application, users need tofirst unregister the application as an administrator.

Policies

In an enterprise setting, it's often the case that employee devices mustadhere to a strict set of policies that govern the use of the device. TheDevice Administration API supports the policies listed in Table 1.Note that the Device Administration API currently only supports passwords for screenlock:

Table 1. Policies supported by the Device Administration API.

Policy Description
Password enabled Requires that devices ask for PIN or passwords.
Minimum password length Set the required number of characters for the password. For example, youcan require PIN or passwords to have at least six characters.
Alphanumeric password required Requires that passwords have acombination of letters and numbers. They may include symbolic characters.
Complex password required Requires that passwords must contain at least a letter, a numerical digit, and a special symbol. Introduced in Android 3.0.
Minimum letters required in password The minimum number ofletters required in the password for all admins or a particular one. Introduced in Android 3.0.
Minimum lowercase letters required in password The minimum number of lowercase letters required in the password for all admins or a particular one. Introduced in Android 3.0.
Minimum non-letter characters required in password The minimum number ofnon-letter characters required in the password for all admins or a particular one. Introduced in Android 3.0.
Minimum numerical digits required in password The minimum number of numerical digits required in the password for all admins or a particular one. Introduced in Android 3.0.
Minimum symbols required in password The minimum number of symbols required in the password for all admins or a particular one. Introduced in Android 3.0.
Minimum uppercase letters required in password The minimum number of uppercase letters required in the password for all admins or a particular one. Introduced in Android 3.0.
Password expiration timeout When the password will expire, expressed as a delta in milliseconds from when a device admin sets the expiration timeout. Introduced in Android 3.0.
Password history restriction This policy prevents users from reusing the last n unique passwords. This policy is typically used in conjunction withsetPasswordExpirationTimeout(), which forcesusers to update their passwords after a specified amount of time has elapsed.Introduced in Android 3.0.
Maximum failed password attempts Specifies how many times a user can enter the wrong password before thedevice wipes its data. The Device Administration API also allows administrators toremotely reset the device to factory defaults. This secures data in case thedevice is lost or stolen.
Maximum inactivity time lock Sets the length of time since the user last touched the screen orpressed a button before the device locks the screen. When this happens, usersneed to enter their PIN or passwords again before they can use their devices andaccess data. The value can be between 1 and 60 minutes.
Require storage encryption Specifies that the storage area should be encrypted, if the device supports it. Introduced in Android 3.0.

Other features

In addition to supporting the policies listed in the above table, the DeviceAdministration API lets you do the following:

  • Prompt user to set a new password.
  • Lock device immediately.
  • Wipe the device's data (that is, restore the device to its factory defaults).

Sample Application

The examples used in this document are based on the Device Administration APIsample, which is included in the SDK samples. For information on downloading andinstalling the SDK samples, seeGetting the Samples. Here is thecomplete code forthe sample.

Thesample application offers a demo of device admin features. It presents userswith a user interface that lets them enable the device admin application. Oncethey've enabled the application, they can use the buttons in the user interfaceto do the following:

  • Set password quality.
  • Specify requirements for the user's password, such as minimum length, the minimum number of numeric characters it must contain, and so on.
  • Set the password. If the password does not conform to the specifiedpolicies, the system returns an error.
  • Set how many failed password attempts can occur before the device is wiped(that is, restored to factory settings).
  • Set how long from now the password will expire.
  • Set the password history length (length refers to number of old passwords stored in the history). This prevents users from reusing one of the lastn passwords they previously used.
  • Specify that the storage area should be encrypted, if the device supports it.
  • Set the maximum amount of inactive time that can elapse before the devicelocks.
  • Make the device lock immediately.
  • Wipe the device's data (that is, restore factory settings).
Android 设备管理_第1张图片

Figure 1. Screenshot of the Sample Application

Developing a Device Administration Application

System administrators can use the Device Administration API to write an applicationthat enforces remote/local device security policy enforcement. This sectionsummarizes the steps involved in creating a device administrationapplication.

Creating the manifest

To use the Device Administration API, the application'smanifest must include the following:

  • A subclass of DeviceAdminReceiver that includes the following:
    • The BIND_DEVICE_ADMIN permission.
    • The ability to respond to the ACTION_DEVICE_ADMIN_ENABLEDintent, expressed in the manifest as an intent filter.
  • A declaration of security policies used in metadata.

Here is an excerpt from the Device Administration sample manifest:

<activity android:name=".app.DeviceAdminSample$Controller"
          android:label="@string/activity_sample_device_admin">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.SAMPLE_CODE" />
    </intent-filter>
</activity>

<receiver android:name=".app.DeviceAdminSample"
          android:label="@string/sample_device_admin"
          android:description="@string/sample_device_admin_description"
          android:permission="android.permission.BIND_DEVICE_ADMIN">
    <meta-data android:name="android.app.device_admin"
               android:resource="@xml/device_admin_sample" />
    <intent-filter>
        <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
    </intent-filter>
</receiver>

Note that:

  • The activity in the sample application is an Activitysubclass calledController. The syntax".app.DeviceAdminSample$Controller" indicates thatController is an inner class that is nested inside theDeviceAdminSample class. Note that an Activity does not need to bean inner class; it just is in this example.
  • The following attributes refer to string resources that for the sample application reside inApiDemos/res/values/strings.xml. For more information about resources, seeApplication Resources.
    • android:label="@string/activity_sample_device_admin" refers to theuser-readable label for the activity.
    • android:label="@string/sample_device_admin" refers to theuser-readable label for the permission.
    • android:description="@string/sample_device_admin_description" refers tothe user-readable description of the permission. A descripton is typically longer and moreinformative thana label.
  • android:permission="android.permission.BIND_DEVICE_ADMIN" is a permission that aDeviceAdminReceiver subclass musthave, to ensure that only the system can interact with the receiver (no application can be granted this permission). Thisprevents other applications from abusing your device admin app.
  • android.app.action.DEVICE_ADMIN_ENABLED is the the primaryaction that aDeviceAdminReceiver subclass must handle to beallowed to manage a device. This is set to the receiver when the user enablesthe device admin app. Your code typically handles this inonEnabled(). To be supported, the receiver must alsorequire the BIND_DEVICE_ADMIN permission so that other applicationscannot abuse it.
  • When a user enables the device admin application, that gives the receiverpermission to perform actions in response to the broadcast of particular systemevents. When suitable event arises, the application can impose a policy. Forexample, if the user attempts to set a new password that doesn't meet the policyrequirements, the application can prompt the user to pick a different passwordthat does meet the requirements.
  • android:resource="@xml/device_admin_sample"declares the security policies used in metadata. The metadata provides additionalinformation specific to the device administrator, as parsed by theDeviceAdminInfo class. Here are the contents ofdevice_admin_sample.xml:
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
  <uses-policies>
    <limit-password />
    <watch-login />
    <reset-password />
    <force-lock />
    <wipe-data />
  </uses-policies>
</device-admin>

In designing your device administration application, you don't need toinclude all of the policies, just the ones that are relevant for your app.

For more discussion of the manifest file, see the Android Developers Guide.

Implementing the code

The Device Administration API includes the following classes:

DeviceAdminReceiver
Base class for implementing a device administration component. This class providesa convenience for interpreting the raw intent actions that are sent by thesystem. Your Device Administration application must include a DeviceAdminReceiver subclass.
DevicePolicyManager
A class for managing policies enforced on a device. Most clients ofthis class must have published a DeviceAdminReceiver that the userhas currently enabled. The DevicePolicyManager manages policies forone or more DeviceAdminReceiver instances
DeviceAdminInfo
This class is used to specify metadatafor a device administrator component.

These classes provide the foundation for a fully functional device administration application.The rest of this section describes how you use theDeviceAdminReceiver andDevicePolicyManager APIs to write a device admin application.

Subclassing DeviceAdminReceiver

To create a device admin application, you must subclassDeviceAdminReceiver. TheDeviceAdminReceiver classconsists of a series of callbacks that are triggered when particular eventsoccur.

In its DeviceAdminReceiver subclass, the sample applicationsimply displays aToast notification in response to particularevents. For example:

public class DeviceAdminSample extends DeviceAdminReceiver {

...
    @Override
    public void onEnabled(Context context, Intent intent) {
        showToast(context, "Sample Device Admin: enabled");
    }

    @Override
    public CharSequence onDisableRequested(Context context, Intent intent) {
        return "This is an optional message to warn the user about disabling.";
    }

    @Override
    public void onDisabled(Context context, Intent intent) {
        showToast(context, "Sample Device Admin: disabled");
    }

    @Override
    public void onPasswordChanged(Context context, Intent intent) {
        showToast(context, "Sample Device Admin: pw changed");
    }

    void showToast(Context context, CharSequence msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }
...
}

Enabling the application

One of the major events a device admin application has to handle is the userenabling the application. The user must explicitly enable the application forthe policies to be enforced. If the user chooses not to enable the applicationit will still be present on the device, but its policies will not be enforced, and the user will notget any of the application's benefits.

The process of enabling the application begins when the user performs anaction that triggers theACTION_ADD_DEVICE_ADMINintent. In thesample application, this happens when the user clicks theEnableAdmin button.

When the user clicks the Enable Admin button, the displaychanges to prompt the user to enable the device admin application, as shown in figure2.

Android 设备管理_第2张图片

Figure 2. Sample Application: Activating the Application

Below is the code that gets executed when the user clicks the EnableAdmin button shown in figure 1.

 private OnClickListener mEnableListener = new OnClickListener() {
    public void onClick(View v) {
        // Launch the activity to have the user enable our admin.
        Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
               mDeviceAdminSample);
        intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
               "Additional text explaining why this needs to be added.");
        startActivityForResult(intent, RESULT_ENABLE);
    }
};

...
// This code checks whether the device admin app was successfully enabled.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case RESULT_ENABLE:
            if (resultCode == Activity.RESULT_OK) {
                Log.i("DeviceAdminSample", "Administration enabled!");
            } else {
                Log.i("DeviceAdminSample", "Administration enable FAILED!");
            }
            return;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

The lineintent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,mDeviceAdminSample) states thatmDeviceAdminSample (which isa DeviceAdminReceiver component) is the target policy.This line invokes the user interface shown in figure 2, which guides users throughadding the device administrator to the system (or allows them to reject it).

When the application needs to perform an operation that is contingent on thedevice admin application being enabled, it confirms that the application isactive. To do this it uses theDevicePolicyManager methodisAdminActive(). Notice that the DevicePolicyManagermethodisAdminActive() takes aDeviceAdminReceivercomponent as its argument:

DevicePolicyManager mDPM;
...
boolean active = mDPM.isAdminActive(mDeviceAdminSample);
if (active) {
    // Admin app is active, so do some admin stuff
               ...
} else {
    // do something else
}

Managing policies

DevicePolicyManager is a public class for managing policiesenforced on a device.DevicePolicyManager manages policies for oneor moreDeviceAdminReceiver instances.

You get a handle to the DevicePolicyManager as follows:

DevicePolicyManager mDPM =
    (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);

This section describes how to use DevicePolicyManager to perform administrative tasks:

  • Set password policies
  • Set device lock
  • Perform data wipe

Set password policies

DevicePolicyManager includes APIs for setting and enforcing thedevice password policy. In the Device Administration API, the password only applies toscreen lock. This section describes common password-related tasks.

Set a password for the device

This code displays a user interface prompting the user to set a password:

Intent intent = new Intent(DevicePolicyManager.ACTION_SET_NEW_PASSWORD);
startActivity(intent);
Set the password quality

The password quality can be one of the following DevicePolicyManager constants:

PASSWORD_QUALITY_ALPHABETIC
The user must enter apassword containing at least alphabetic (or other symbol) characters.
PASSWORD_QUALITY_ALPHANUMERIC
The user must enter apassword containing at least both numeric and alphabetic (orother symbol) characters.
PASSWORD_QUALITY_NUMERIC
The user must enter a passwordcontaining at least numeric characters.
PASSWORD_QUALITY_COMPLEX
The usermust have entered a password containing at least a letter, a numerical digit anda special symbol.
PASSWORD_QUALITY_SOMETHING
Thepolicy requires some kindof password, but doesn't care what it is.
PASSWORD_QUALITY_UNSPECIFIED
The policy has no requirements for the password.

For example, this is how you would set the password policy to require an alphanumeric password:

DevicePolicyManager mDPM;
ComponentName mDeviceAdminSample;
...
mDPM.setPasswordQuality(mDeviceAdminSample, DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC);
Set password content requirements

Beginning with Android 3.0, the DevicePolicyManager classincludes methods that let you fine-tune the contents of the password. Forexample, you could set a policy that states that passwords must contain at leastn uppercase letters. Here are the methods for fine-tuning a password'scontents:

  • setPasswordMinimumLetters()
  • setPasswordMinimumLowerCase()
  • setPasswordMinimumUpperCase()
  • setPasswordMinimumNonLetter()
  • setPasswordMinimumNumeric()
  • setPasswordMinimumSymbols()

For example, this snippet states that the password must have at least 2 uppercase letters:

DevicePolicyManager mDPM;
ComponentName mDeviceAdminSample;
int pwMinUppercase = 2;
...
mDPM.setPasswordMinimumUpperCase(mDeviceAdminSample, pwMinUppercase);
Set the minimum password length

You can specify that a password must be at least the specified minimumlength. For example:

DevicePolicyManager mDPM;
ComponentName mDeviceAdminSample;
int pwLength;
...
mDPM.setPasswordMinimumLength(mDeviceAdminSample, pwLength);
Set maximum failed password attempts

You can set the maximum number of allowed failed password attempts before thedevice is wiped (that is, reset to factory settings). For example:

DevicePolicyManager mDPM;
ComponentName mDeviceAdminSample;
int maxFailedPw;
 ...
mDPM.setMaximumFailedPasswordsForWipe(mDeviceAdminSample, maxFailedPw);
Set password expiration timeout

Beginning with Android 3.0, you can use the setPasswordExpirationTimeout() method to set when a password will expire, expressed as a delta in milliseconds from when a device admin sets the expiration timeout. For example:

DevicePolicyManager mDPM;
ComponentName mDeviceAdminSample;
long pwExpiration;
...
mDPM.setPasswordExpirationTimeout(mDeviceAdminSample, pwExpiration);

From the Device Administration API sample, here is the codethat updates the password expiration status:

DevicePolicyManager mDPM;
ComponentName mDeviceAdminSample;
private TextView mPasswordExpirationStatus;
...
void updatePasswordExpirationStatus() {
    boolean active = mDPM.isAdminActive(mDeviceAdminSample);
    String statusText;
    if (active) {
        long now = System.currentTimeMillis();
        // Query the DevicePolicyManager twice - first for the expiration values
        // set by the sample app, and later, for the system values (which may be different
        // if there is another administrator active.)
        long expirationDate = mDPM.getPasswordExpiration(mDeviceAdminSample);
        long mSecUntilExpiration = expirationDate - now;
        if (mSecUntilExpiration >= 0) {
            statusText = "Expiration in " + countdownString(mSecUntilExpiration);
        } else {
            statusText = "Expired " + countdownString(-mSecUntilExpiration) + " ago";
        }

        // expirationTimeout is the cycle time between required password refresh
        long expirationTimeout = mDPM.getPasswordExpirationTimeout(mDeviceAdminSample);
        statusText += " / timeout period " + countdownString(expirationTimeout);

        // Now report the aggregate (global) expiration time
        statusText += " / Aggregate ";
        expirationDate = mDPM.getPasswordExpiration(null);
        mSecUntilExpiration = expirationDate - now;
        if (mSecUntilExpiration >= 0) {
            statusText += "expiration in " + countdownString(mSecUntilExpiration);
        } else {
            statusText += "expired " + countdownString(-mSecUntilExpiration) + " ago";
        }
    } else {
        statusText = "<inactive>";
    }
    mPasswordExpirationStatus.setText(statusText);
Restrict password based on history

Beginning with Android 3.0, you can use the setPasswordHistoryLength() method to limit users'ability to reuse old passwords. This method takes a lengthparameter, which specifies how many oldpasswords are stored. When this policy is active, users cannot enter a newpassword that matches the lastn passwords. This preventsusers from using the same password over and over. This policy is typically usedin conjunction withsetPasswordExpirationTimeout(),which forces usersto update their passwords after a specified amount of time has elapsed.

For example, this snippet prohibits users from reusing any of their last 5 passwords:

DevicePolicyManager mDPM;
ComponentName mDeviceAdminSample;
int pwHistoryLength = 5;
...
mDPM.setPasswordHistoryLength(mDeviceAdminSample, pwHistoryLength);

Set device lock

You can set the maximum period of user inactivity that can occur before thedevice locks. For example:

DevicePolicyManager mDPM;
ComponentName mDeviceAdminSample;
...
long timeMs = 1000L*Long.parseLong(mTimeout.getText().toString());
mDPM.setMaximumTimeToLock(mDeviceAdminSample, timeMs);

You can also programmatically tell the device to lock immediately:

DevicePolicyManager mDPM;
mDPM.lockNow();

Perform data wipe

You can use the DevicePolicyManager methodwipeData() to reset the device to factory settings. This is usefulif the device is lost or stolen. Often the decision to wipe the device is theresult of certain conditions being met. For example, you can usesetMaximumFailedPasswordsForWipe() to state that a device should bewiped after a specific number of failed password attempts.

You wipe data as follows:

DevicePolicyManager mDPM;
mDPM.wipeData(0);

The wipeData() method takes as its parameter a bit mask ofadditional options. Currently the value must be 0.

Storage encryption

Beginning with Android 3.0, you can use the setStorageEncryption() method to set a policy requiring encryption of the storage area, where supported.

For example:

DevicePolicyManager mDPM;
ComponentName mDeviceAdminSample;
...
mDPM.setStorageEncryption(mDeviceAdminSample, true);

See the Device Administration API sample for a completeexample of how to enable storage encryption.


你可能感兴趣的:(android,api,Security,user,application,passwords)