TrustAgentService.java revision 18ea893a2319e2a192188d2288bb881149c9b06e
1/**
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.service.trust;
18
19import android.Manifest;
20import android.annotation.SdkConstant;
21import android.app.Service;
22import android.content.ComponentName;
23import android.content.Intent;
24import android.content.pm.PackageManager;
25import android.content.pm.ServiceInfo;
26import android.os.Handler;
27import android.os.IBinder;
28import android.os.RemoteException;
29import android.util.Log;
30import android.util.Slog;
31
32/**
33 * A service that notifies the system about whether it believes the environment of the device
34 * to be trusted.
35 *
36 * <p>Trust agents may only be provided by the platform.</p>
37 *
38 * <p>To extend this class, you must declare the service in your manifest file with
39 * the {@link android.Manifest.permission#BIND_TRUST_AGENT} permission
40 * and include an intent filter with the {@link #SERVICE_INTERFACE} action. For example:</p>
41 * <pre>
42 * &lt;service android:name=".TrustAgent"
43 *          android:label="&#64;string/service_name"
44 *          android:permission="android.permission.BIND_TRUST_AGENT">
45 *     &lt;intent-filter>
46 *         &lt;action android:name="android.service.trust.TrustAgentService" />
47 *     &lt;/intent-filter>
48 *     &lt;meta-data android:name="android.service.trust.trustagent"
49 *          android:value="&#64;xml/trust_agent" />
50 * &lt;/service></pre>
51 *
52 * <p>The associated meta-data file can specify an activity that is accessible through Settings
53 * and should allow configuring the trust agent, as defined in
54 * {@link android.R.styleable#TrustAgent}. For example:</p>
55 *
56 * <pre>
57 * &lt;trust-agent xmlns:android="http://schemas.android.com/apk/res/android"
58 *          android:settingsActivity=".TrustAgentSettings" /></pre>
59 */
60public class TrustAgentService extends Service {
61    private final String TAG = TrustAgentService.class.getSimpleName() +
62            "[" + getClass().getSimpleName() + "]";
63
64    /**
65     * The {@link Intent} that must be declared as handled by the service.
66     */
67    @SdkConstant(SdkConstant.SdkConstantType.SERVICE_ACTION)
68    public static final String SERVICE_INTERFACE
69            = "android.service.trust.TrustAgentService";
70
71    /**
72     * The name of the {@code meta-data} tag pointing to additional configuration of the trust
73     * agent.
74     */
75    public static final String TRUST_AGENT_META_DATA = "android.service.trust.trustagent";
76
77    private static final int MSG_UNLOCK_ATTEMPT = 1;
78
79    private static final boolean DEBUG = false;
80
81    private ITrustAgentServiceCallback mCallback;
82
83    private Handler mHandler = new Handler() {
84        public void handleMessage(android.os.Message msg) {
85            switch (msg.what) {
86                case MSG_UNLOCK_ATTEMPT:
87                    onUnlockAttempt(msg.arg1 != 0);
88                    break;
89            }
90        };
91    };
92
93    @Override
94    public void onCreate() {
95        super.onCreate();
96        ComponentName component = new ComponentName(this, getClass());
97        try {
98            ServiceInfo serviceInfo = getPackageManager().getServiceInfo(component, 0 /* flags */);
99            if (!Manifest.permission.BIND_TRUST_AGENT.equals(serviceInfo.permission)) {
100                throw new IllegalStateException(component.flattenToShortString()
101                        + " is not declared with the permission "
102                        + "\"" + Manifest.permission.BIND_TRUST_AGENT + "\"");
103            }
104        } catch (PackageManager.NameNotFoundException e) {
105            Log.e(TAG, "Can't get ServiceInfo for " + component.toShortString());
106        }
107    }
108
109    /**
110     * Called when the user attempted to authenticate on the device.
111     *
112     * @param successful true if the attempt succeeded
113     */
114    public void onUnlockAttempt(boolean successful) {
115    }
116
117    private void onError(String msg) {
118        Slog.v(TAG, "Remote exception while " + msg);
119    }
120
121    /**
122     * Call to grant trust on the device.
123     *
124     * @param message describes why the device is trusted, e.g. "Trusted by location".
125     * @param durationMs amount of time in milliseconds to keep the device in a trusted state. Trust
126     *                   for this agent will automatically be revoked when the timeout expires.
127     * @param initiatedByUser indicates that the user has explicitly initiated an action that proves
128     *                        the user is about to use the device.
129     */
130    public final void grantTrust(CharSequence message, long durationMs, boolean initiatedByUser) {
131        if (mCallback != null) {
132            try {
133                mCallback.grantTrust(message.toString(), durationMs, initiatedByUser);
134            } catch (RemoteException e) {
135                onError("calling enableTrust()");
136            }
137        }
138    }
139
140    /**
141     * Call to revoke trust on the device.
142     */
143    public final void revokeTrust() {
144        if (mCallback != null) {
145            try {
146                mCallback.revokeTrust();
147            } catch (RemoteException e) {
148                onError("calling revokeTrust()");
149            }
150        }
151    }
152
153    @Override
154    public final IBinder onBind(Intent intent) {
155        if (DEBUG) Slog.v(TAG, "onBind() intent = " + intent);
156        return new TrustAgentServiceWrapper();
157    }
158
159    private final class TrustAgentServiceWrapper extends ITrustAgentService.Stub {
160        @Override
161        public void onUnlockAttempt(boolean successful) {
162            mHandler.obtainMessage(MSG_UNLOCK_ATTEMPT, successful ? 1 : 0, 0)
163                    .sendToTarget();
164        }
165
166        public void setCallback(ITrustAgentServiceCallback callback) {
167            mCallback = callback;
168        }
169    }
170
171}
172