1 /*
2 * Copyright (C) 2015 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
17 #define LOG_TAG "gatekeeperd"
18
19 #include "IGateKeeperService.h"
20
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <inttypes.h>
24 #include <stdint.h>
25 #include <unistd.h>
26 #include <memory>
27
28 #include <android/security/keystore/IKeystoreService.h>
29 #include <android-base/logging.h>
30 #include <android-base/properties.h>
31 #include <binder/IPCThreadState.h>
32 #include <binder/IServiceManager.h>
33 #include <binder/PermissionCache.h>
34 #include <gatekeeper/password_handle.h> // for password_handle_t
35 #include <hardware/gatekeeper.h>
36 #include <hardware/hw_auth_token.h>
37 #include <keystore/keystore.h> // For error code
38 #include <keystore/keystore_return_types.h>
39 #include <libgsi/libgsi.h>
40 #include <log/log.h>
41 #include <utils/Log.h>
42 #include <utils/String16.h>
43
44 #include "SoftGateKeeperDevice.h"
45
46 #include <hidl/HidlSupport.h>
47 #include <android/hardware/gatekeeper/1.0/IGatekeeper.h>
48
49 using android::sp;
50 using android::hardware::gatekeeper::V1_0::IGatekeeper;
51 using android::hardware::gatekeeper::V1_0::GatekeeperStatusCode;
52 using android::hardware::gatekeeper::V1_0::GatekeeperResponse;
53 using android::hardware::Return;
54
55 namespace android {
56
57 static const String16 KEYGUARD_PERMISSION("android.permission.ACCESS_KEYGUARD_SECURE_STORAGE");
58 static const String16 DUMP_PERMISSION("android.permission.DUMP");
59
60 class GateKeeperProxy : public BnGateKeeperService {
61 public:
GateKeeperProxy()62 GateKeeperProxy() {
63 clear_state_if_needed_done = false;
64 hw_device = IGatekeeper::getService();
65 is_running_gsi = android::base::GetBoolProperty(android::gsi::kGsiBootedProp, false);
66
67 if (hw_device == nullptr) {
68 ALOGW("falling back to software GateKeeper");
69 soft_device.reset(new SoftGateKeeperDevice());
70 }
71 }
72
~GateKeeperProxy()73 virtual ~GateKeeperProxy() {
74 }
75
store_sid(uint32_t uid,uint64_t sid)76 void store_sid(uint32_t uid, uint64_t sid) {
77 char filename[21];
78 snprintf(filename, sizeof(filename), "%u", uid);
79 int fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR);
80 if (fd < 0) {
81 ALOGE("could not open file: %s: %s", filename, strerror(errno));
82 return;
83 }
84 write(fd, &sid, sizeof(sid));
85 close(fd);
86 }
87
clear_state_if_needed()88 void clear_state_if_needed() {
89 if (clear_state_if_needed_done) {
90 return;
91 }
92
93 if (mark_cold_boot() && !is_running_gsi) {
94 ALOGI("cold boot: clearing state");
95 if (hw_device != nullptr) {
96 hw_device->deleteAllUsers([](const GatekeeperResponse &){});
97 }
98 }
99
100 clear_state_if_needed_done = true;
101 }
102
mark_cold_boot()103 bool mark_cold_boot() {
104 const char *filename = ".coldboot";
105 if (access(filename, F_OK) == -1) {
106 int fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR);
107 if (fd < 0) {
108 ALOGE("could not open file: %s : %s", filename, strerror(errno));
109 return false;
110 }
111 close(fd);
112 return true;
113 }
114 return false;
115 }
116
maybe_store_sid(uint32_t uid,uint64_t sid)117 void maybe_store_sid(uint32_t uid, uint64_t sid) {
118 char filename[21];
119 snprintf(filename, sizeof(filename), "%u", uid);
120 if (access(filename, F_OK) == -1) {
121 store_sid(uid, sid);
122 }
123 }
124
read_sid(uint32_t uid)125 uint64_t read_sid(uint32_t uid) {
126 char filename[21];
127 uint64_t sid;
128 snprintf(filename, sizeof(filename), "%u", uid);
129 int fd = open(filename, O_RDONLY);
130 if (fd < 0) return 0;
131 read(fd, &sid, sizeof(sid));
132 close(fd);
133 return sid;
134 }
135
clear_sid(uint32_t uid)136 void clear_sid(uint32_t uid) {
137 char filename[21];
138 snprintf(filename, sizeof(filename), "%u", uid);
139 if (remove(filename) < 0) {
140 ALOGE("%s: could not remove file [%s], attempting 0 write", __func__, strerror(errno));
141 store_sid(uid, 0);
142 }
143 }
144
145 // This should only be called on uids being passed to the GateKeeper HAL. It ensures that
146 // secure storage shared across a GSI image and a host image will not overlap.
adjust_uid(uint32_t uid)147 uint32_t adjust_uid(uint32_t uid) {
148 static constexpr uint32_t kGsiOffset = 1000000;
149 CHECK(uid < kGsiOffset);
150 CHECK(hw_device != nullptr);
151 if (is_running_gsi) {
152 return uid + kGsiOffset;
153 }
154 return uid;
155 }
156
enroll(uint32_t uid,const uint8_t * current_password_handle,uint32_t current_password_handle_length,const uint8_t * current_password,uint32_t current_password_length,const uint8_t * desired_password,uint32_t desired_password_length,uint8_t ** enrolled_password_handle,uint32_t * enrolled_password_handle_length)157 virtual int enroll(uint32_t uid,
158 const uint8_t *current_password_handle, uint32_t current_password_handle_length,
159 const uint8_t *current_password, uint32_t current_password_length,
160 const uint8_t *desired_password, uint32_t desired_password_length,
161 uint8_t **enrolled_password_handle, uint32_t *enrolled_password_handle_length) {
162 IPCThreadState* ipc = IPCThreadState::self();
163 const int calling_pid = ipc->getCallingPid();
164 const int calling_uid = ipc->getCallingUid();
165 if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
166 return PERMISSION_DENIED;
167 }
168
169 // Make sure to clear any state from before factory reset as soon as a credential is
170 // enrolled (which may happen during device setup).
171 clear_state_if_needed();
172
173 // need a desired password to enroll
174 if (desired_password_length == 0) return -EINVAL;
175
176 int ret;
177 if (hw_device != nullptr) {
178 const gatekeeper::password_handle_t *handle =
179 reinterpret_cast<const gatekeeper::password_handle_t *>(current_password_handle);
180
181 if (handle != NULL && handle->version != 0 && !handle->hardware_backed) {
182 // handle is being re-enrolled from a software version. HAL probably won't accept
183 // the handle as valid, so we nullify it and enroll from scratch
184 current_password_handle = NULL;
185 current_password_handle_length = 0;
186 current_password = NULL;
187 current_password_length = 0;
188 }
189
190 android::hardware::hidl_vec<uint8_t> curPwdHandle;
191 curPwdHandle.setToExternal(const_cast<uint8_t*>(current_password_handle),
192 current_password_handle_length);
193 android::hardware::hidl_vec<uint8_t> curPwd;
194 curPwd.setToExternal(const_cast<uint8_t*>(current_password),
195 current_password_length);
196 android::hardware::hidl_vec<uint8_t> newPwd;
197 newPwd.setToExternal(const_cast<uint8_t*>(desired_password),
198 desired_password_length);
199
200 uint32_t hw_uid = adjust_uid(uid);
201 Return<void> hwRes = hw_device->enroll(hw_uid, curPwdHandle, curPwd, newPwd,
202 [&ret, enrolled_password_handle, enrolled_password_handle_length]
203 (const GatekeeperResponse &rsp) {
204 ret = static_cast<int>(rsp.code); // propagate errors
205 if (rsp.code >= GatekeeperStatusCode::STATUS_OK) {
206 if (enrolled_password_handle != nullptr &&
207 enrolled_password_handle_length != nullptr) {
208 *enrolled_password_handle = new uint8_t[rsp.data.size()];
209 *enrolled_password_handle_length = rsp.data.size();
210 memcpy(*enrolled_password_handle, rsp.data.data(),
211 *enrolled_password_handle_length);
212 }
213 ret = 0; // all success states are reported as 0
214 } else if (rsp.code == GatekeeperStatusCode::ERROR_RETRY_TIMEOUT && rsp.timeout > 0) {
215 ret = rsp.timeout;
216 }
217 });
218 if (!hwRes.isOk()) {
219 ALOGE("enroll transaction failed\n");
220 ret = -1;
221 }
222 } else {
223 ret = soft_device->enroll(uid,
224 current_password_handle, current_password_handle_length,
225 current_password, current_password_length,
226 desired_password, desired_password_length,
227 enrolled_password_handle, enrolled_password_handle_length);
228 }
229
230 if (ret == GATEKEEPER_RESPONSE_OK && (*enrolled_password_handle == nullptr ||
231 *enrolled_password_handle_length != sizeof(password_handle_t))) {
232 ret = GATEKEEPER_RESPONSE_ERROR;
233 ALOGE("HAL: password_handle=%p size_of_handle=%" PRIu32 "\n",
234 *enrolled_password_handle, *enrolled_password_handle_length);
235 }
236
237 if (ret == GATEKEEPER_RESPONSE_OK) {
238 gatekeeper::password_handle_t *handle =
239 reinterpret_cast<gatekeeper::password_handle_t *>(*enrolled_password_handle);
240 store_sid(uid, handle->user_id);
241 bool rr;
242
243 // immediately verify this password so we don't ask the user to enter it again
244 // if they just created it.
245 verify(uid, *enrolled_password_handle, sizeof(password_handle_t), desired_password,
246 desired_password_length, &rr);
247 }
248
249 return ret;
250 }
251
verify(uint32_t uid,const uint8_t * enrolled_password_handle,uint32_t enrolled_password_handle_length,const uint8_t * provided_password,uint32_t provided_password_length,bool * request_reenroll)252 virtual int verify(uint32_t uid,
253 const uint8_t *enrolled_password_handle, uint32_t enrolled_password_handle_length,
254 const uint8_t *provided_password, uint32_t provided_password_length, bool *request_reenroll) {
255 uint8_t *auth_token = nullptr;
256 uint32_t auth_token_length;
257 int ret = verifyChallenge(uid, 0, enrolled_password_handle, enrolled_password_handle_length,
258 provided_password, provided_password_length,
259 &auth_token, &auth_token_length, request_reenroll);
260 delete [] auth_token;
261 return ret;
262 }
263
verifyChallenge(uint32_t uid,uint64_t challenge,const uint8_t * enrolled_password_handle,uint32_t enrolled_password_handle_length,const uint8_t * provided_password,uint32_t provided_password_length,uint8_t ** auth_token,uint32_t * auth_token_length,bool * request_reenroll)264 virtual int verifyChallenge(uint32_t uid, uint64_t challenge,
265 const uint8_t *enrolled_password_handle, uint32_t enrolled_password_handle_length,
266 const uint8_t *provided_password, uint32_t provided_password_length,
267 uint8_t **auth_token, uint32_t *auth_token_length, bool *request_reenroll) {
268 IPCThreadState* ipc = IPCThreadState::self();
269 const int calling_pid = ipc->getCallingPid();
270 const int calling_uid = ipc->getCallingUid();
271 if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
272 return PERMISSION_DENIED;
273 }
274
275 // can't verify if we're missing either param
276 if (enrolled_password_handle == nullptr || provided_password == nullptr ||
277 enrolled_password_handle_length == 0 || provided_password_length == 0)
278 return -EINVAL;
279
280 int ret;
281 if (hw_device != nullptr) {
282 const gatekeeper::password_handle_t *handle =
283 reinterpret_cast<const gatekeeper::password_handle_t *>(enrolled_password_handle);
284 // handle version 0 does not have hardware backed flag, and thus cannot be upgraded to
285 // a HAL if there was none before
286 if (handle->version == 0 || handle->hardware_backed) {
287 uint32_t hw_uid = adjust_uid(uid);
288 android::hardware::hidl_vec<uint8_t> curPwdHandle;
289 curPwdHandle.setToExternal(const_cast<uint8_t*>(enrolled_password_handle),
290 enrolled_password_handle_length);
291 android::hardware::hidl_vec<uint8_t> enteredPwd;
292 enteredPwd.setToExternal(const_cast<uint8_t*>(provided_password),
293 provided_password_length);
294 Return<void> hwRes = hw_device->verify(hw_uid, challenge, curPwdHandle, enteredPwd,
295 [&ret, request_reenroll, auth_token, auth_token_length]
296 (const GatekeeperResponse &rsp) {
297 ret = static_cast<int>(rsp.code); // propagate errors
298 if (auth_token != nullptr && auth_token_length != nullptr &&
299 rsp.code >= GatekeeperStatusCode::STATUS_OK) {
300 *auth_token = new uint8_t[rsp.data.size()];
301 *auth_token_length = rsp.data.size();
302 memcpy(*auth_token, rsp.data.data(), *auth_token_length);
303 if (request_reenroll != nullptr) {
304 *request_reenroll = (rsp.code == GatekeeperStatusCode::STATUS_REENROLL);
305 }
306 ret = 0; // all success states are reported as 0
307 } else if (rsp.code == GatekeeperStatusCode::ERROR_RETRY_TIMEOUT &&
308 rsp.timeout > 0) {
309 ret = rsp.timeout;
310 }
311 });
312 if (!hwRes.isOk()) {
313 ALOGE("verify transaction failed\n");
314 ret = -1;
315 }
316 } else {
317 // upgrade scenario, a HAL has been added to this device where there was none before
318 SoftGateKeeperDevice soft_dev;
319 ret = soft_dev.verify(uid, challenge,
320 enrolled_password_handle, enrolled_password_handle_length,
321 provided_password, provided_password_length, auth_token, auth_token_length,
322 request_reenroll);
323
324 if (ret == 0) {
325 // success! re-enroll with HAL
326 if (request_reenroll != nullptr) *request_reenroll = true;
327 }
328 }
329 } else {
330 ret = soft_device->verify(uid, challenge,
331 enrolled_password_handle, enrolled_password_handle_length,
332 provided_password, provided_password_length, auth_token, auth_token_length,
333 request_reenroll);
334 }
335
336 if (ret == 0 && *auth_token != NULL && *auth_token_length > 0) {
337 // TODO: cache service?
338 sp<IServiceManager> sm = defaultServiceManager();
339 sp<IBinder> binder = sm->getService(String16("android.security.keystore"));
340 sp<security::keystore::IKeystoreService> service =
341 interface_cast<security::keystore::IKeystoreService>(binder);
342 if (service != NULL) {
343 std::vector<uint8_t> auth_token_vector(*auth_token,
344 (*auth_token) + *auth_token_length);
345 int result = 0;
346 auto binder_result = service->addAuthToken(auth_token_vector, &result);
347 if (!binder_result.isOk() || !keystore::KeyStoreServiceReturnCode(result).isOk()) {
348 ALOGE("Failure sending auth token to KeyStore: %" PRId32, result);
349 }
350 } else {
351 ALOGE("Unable to communicate with KeyStore");
352 }
353 }
354
355 if (ret == 0) {
356 maybe_store_sid(uid, reinterpret_cast<const gatekeeper::password_handle_t *>(
357 enrolled_password_handle)->user_id);
358 }
359
360 return ret;
361 }
362
getSecureUserId(uint32_t uid)363 virtual uint64_t getSecureUserId(uint32_t uid) { return read_sid(uid); }
364
clearSecureUserId(uint32_t uid)365 virtual void clearSecureUserId(uint32_t uid) {
366 IPCThreadState* ipc = IPCThreadState::self();
367 const int calling_pid = ipc->getCallingPid();
368 const int calling_uid = ipc->getCallingUid();
369 if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
370 ALOGE("%s: permission denied for [%d:%d]", __func__, calling_pid, calling_uid);
371 return;
372 }
373 clear_sid(uid);
374
375 if (hw_device != nullptr) {
376 uint32_t hw_uid = adjust_uid(uid);
377 hw_device->deleteUser(hw_uid, [] (const GatekeeperResponse &){});
378 }
379 }
380
reportDeviceSetupComplete()381 virtual void reportDeviceSetupComplete() {
382 IPCThreadState* ipc = IPCThreadState::self();
383 const int calling_pid = ipc->getCallingPid();
384 const int calling_uid = ipc->getCallingUid();
385 if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
386 ALOGE("%s: permission denied for [%d:%d]", __func__, calling_pid, calling_uid);
387 return;
388 }
389
390 clear_state_if_needed();
391 }
392
dump(int fd,const Vector<String16> &)393 virtual status_t dump(int fd, const Vector<String16> &) {
394 IPCThreadState* ipc = IPCThreadState::self();
395 const int pid = ipc->getCallingPid();
396 const int uid = ipc->getCallingUid();
397 if (!PermissionCache::checkPermission(DUMP_PERMISSION, pid, uid)) {
398 return PERMISSION_DENIED;
399 }
400
401 if (hw_device == NULL) {
402 const char *result = "Device not available";
403 write(fd, result, strlen(result) + 1);
404 } else {
405 const char *result = "OK";
406 write(fd, result, strlen(result) + 1);
407 }
408
409 return OK;
410 }
411
412 private:
413 sp<IGatekeeper> hw_device;
414 std::unique_ptr<SoftGateKeeperDevice> soft_device;
415
416 bool clear_state_if_needed_done;
417 bool is_running_gsi;
418 };
419 }// namespace android
420
main(int argc,char * argv[])421 int main(int argc, char* argv[]) {
422 ALOGI("Starting gatekeeperd...");
423 if (argc < 2) {
424 ALOGE("A directory must be specified!");
425 return 1;
426 }
427 if (chdir(argv[1]) == -1) {
428 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
429 return 1;
430 }
431
432 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
433 android::sp<android::GateKeeperProxy> proxy = new android::GateKeeperProxy();
434 android::status_t ret = sm->addService(
435 android::String16("android.service.gatekeeper.IGateKeeperService"), proxy);
436 if (ret != android::OK) {
437 ALOGE("Couldn't register binder service!");
438 return -1;
439 }
440
441 /*
442 * We're the only thread in existence, so we're just going to process
443 * Binder transaction as a single-threaded program.
444 */
445 android::IPCThreadState::self()->joinThreadPool();
446 return 0;
447 }
448