summaryrefslogtreecommitdiffstats
blob: 4b587d14195e7a7d12bed3cc50ed6c11e1703a3b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License
 */
package com.android.car.trust;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.car.trust.ICarTrustAgentBleCallback;
import android.car.trust.ICarTrustAgentBleService;
import android.car.trust.ICarTrustAgentEnrolmentCallback;
import android.car.trust.ICarTrustAgentTokenResponseCallback;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.UserHandle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.TextView;

/**
 * Setup activity that binds {@link CarTrustAgentBleService} and starts the enrolment process.
 */
public class CarEnrolmentActivity extends Activity {

    private static final String TAG = CarEnrolmentActivity.class.getSimpleName();

    private static final String SP_HANDLE_KEY = "sp-test";
    private static final int FINE_LOCATION_REQUEST_CODE = 42;

    /**
     * Receives escrow token callbacks, registered on {@link CarTrustAgentBleService}
     */
    private final ICarTrustAgentTokenResponseCallback mCarTrustAgentTokenResponseCallback =
            new ICarTrustAgentTokenResponseCallback.Stub() {
        @Override
        public void onEscrowTokenAdded(byte[] token, long handle, int uid) {
            runOnUiThread(() -> {
                mPrefs.edit().putLong(SP_HANDLE_KEY, handle).apply();
                Log.d(TAG, "stored new handle for user: " + uid);
            });

            if (mBluetoothDevice == null) {
                Log.e(TAG, "No active bluetooth found to add escrow token");
                return;
            }

            try {
                // Notify the enrolment client that escrow token has been added
                mCarTrustAgentBleService.sendEnrolmentHandle(mBluetoothDevice, handle);
                appendOutputText("Escrow Token Added. Handle: " + handle);
                appendOutputText("Lock and unlock the device to activate token");
            } catch (RemoteException e) {
                Log.e(TAG, "Error sendEnrolmentHandle", e);
            }
        }

        @Override
        public void onEscrowTokenRemoved(long handle, boolean successful) {
            appendOutputText("Escrow token Removed. Handle: " + handle);
        }

        @Override
        public void onEscrowTokenActiveStateChanged(long handle, boolean active) {
            appendOutputText("Is token active? " + active + " handle: " + handle);
        }
    };

    /**
     * Receives BLE state change callbacks, registered on {@link CarTrustAgentBleService}
     */
    private final ICarTrustAgentBleCallback mBleConnectionCallback =
            new ICarTrustAgentBleCallback.Stub() {
        @Override
        public void onBleServerStartSuccess() {
            appendOutputText("Server started");
        }

        @Override
        public void onBleServerStartFailure(int errorCode) {
            appendOutputText("Server failed to start, error code: " + errorCode);
        }

        @Override
        public void onBleDeviceConnected(BluetoothDevice device) {
            mBluetoothDevice = device;
            appendOutputText("Device connected: " + device.getName()
                    + " address: " + device.getAddress());
        }

        @Override
        public void onBleDeviceDisconnected(BluetoothDevice device) {
            mBluetoothDevice = null;
            appendOutputText("Device disconnected: " + device.getName()
                    + " address: " + device.getAddress());
        }
    };

    /**
     * {@link CarTrustAgentBleService} will callback this when receives enrolment data.
     *
     * Here is the place we can prompt to the user on HU whether or not to add this
     * {@link #mBluetoothDevice} as a trust device.
     */
    private final ICarTrustAgentEnrolmentCallback mEnrolmentCallback =
            new ICarTrustAgentEnrolmentCallback.Stub() {
        @Override
        public void onEnrolmentDataReceived(byte[] token) {
            appendOutputText("Enrolment data received ");
            try {
                addEscrowToken(token);
            } catch (RemoteException e) {
                Log.e(TAG, "Error addEscrowToken", e);
            }
        }
    };

    /**
     * Service connection to {@link CarTrustAgentBleService}
     */
    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mCarTrustAgentBleServiceBound = true;
            mCarTrustAgentBleService = ICarTrustAgentBleService.Stub.asInterface(service);
            try {
                mCarTrustAgentBleService.registerBleCallback(mBleConnectionCallback);
                mCarTrustAgentBleService.registerEnrolmentCallback(mEnrolmentCallback);
                mCarTrustAgentBleService.setTokenResponseCallback(
                        mCarTrustAgentTokenResponseCallback);
                mCarTrustAgentBleService.startEnrolmentAdvertising();
            } catch (RemoteException e) {
                Log.e(TAG, "Error startEnrolmentAdvertising", e);
            }
            checkTokenHandle();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            if (mCarTrustAgentBleService != null) {
                try {
                    mCarTrustAgentBleService.unregisterBleCallback(mBleConnectionCallback);
                    mCarTrustAgentBleService.unregisterEnrolmentCallback(mEnrolmentCallback);
                    mCarTrustAgentBleService.setTokenResponseCallback(null);
                    mCarTrustAgentBleService.stopEnrolmentAdvertising();
                } catch (RemoteException e) {
                    Log.e(TAG, "Error unregister callbacks", e);
                }
                mCarTrustAgentBleService = null;
            }
            mCarTrustAgentBleServiceBound = false;
        }
    };

    private TextView mOutputText;
    private BluetoothDevice mBluetoothDevice;
    private ICarTrustAgentBleService mCarTrustAgentBleService;
    private boolean mCarTrustAgentBleServiceBound;
    private SharedPreferences mPrefs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.car_enrolment_activity);
        mOutputText = findViewById(R.id.textfield);
        mPrefs = PreferenceManager.getDefaultSharedPreferences(this /* context */);

        findViewById(R.id.start_button).setOnClickListener((view) -> {
            if (!mCarTrustAgentBleServiceBound) {
                Intent bindIntent = new Intent(this, CarTrustAgentBleService.class);
                bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
            }
        });

        findViewById(R.id.revoke_trust_button).setOnClickListener((view) -> {
            if (mCarTrustAgentBleServiceBound) {
                try {
                    mCarTrustAgentBleService.revokeTrust();
                } catch (RemoteException e) {
                    Log.e(TAG, "Error revokeTrust", e);
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) !=
                PackageManager.PERMISSION_GRANTED) {
            requestPermissions(
                    new String[] { android.Manifest.permission.ACCESS_FINE_LOCATION },
                    FINE_LOCATION_REQUEST_CODE);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();

        if (mCarTrustAgentBleServiceBound) {
            unbindService(mServiceConnection);
            mCarTrustAgentBleServiceBound = false;
        }
    }

    private void appendOutputText(final String text) {
        runOnUiThread(() -> mOutputText.append("\n" + text));
    }

    private void addEscrowToken(byte[] token) throws RemoteException {
        if (!mCarTrustAgentBleServiceBound) {
            Log.e(TAG, "No CarTrustAgentBleService bounded");
            return;
        }
        mCarTrustAgentBleService.addEscrowToken(token, UserHandle.myUserId());
    }

    private void checkTokenHandle() {
        long tokenHandle = mPrefs.getLong(SP_HANDLE_KEY, -1);
        if (tokenHandle != -1) {
            Log.d(TAG, "Checking handle active: " + tokenHandle);
            if (mCarTrustAgentBleServiceBound) {
                try {
                    // Due to the asynchronous nature of isEscrowTokenActive in
                    // TrustAgentService, query result will be delivered via
                    // {@link #mCarTrustAgentTokenResponseCallback}
                    mCarTrustAgentBleService.isEscrowTokenActive(tokenHandle,
                            UserHandle.myUserId());
                } catch (RemoteException e) {
                    Log.e(TAG, "Error isEscrowTokenActive", e);
                }
            }
        } else {
            appendOutputText("No handles found");
        }
    }
}