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 #define LOG_TAG "gatekeeperd"
17 
18 #include "gatekeeperd.h"
19 
20 #include <endian.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <unistd.h>
24 #include <memory>
25 
26 #include <KeyMintUtils.h>
27 #include <android-base/logging.h>
28 #include <android-base/properties.h>
29 #include <android/binder_ibinder.h>
30 #include <android/binder_manager.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/hw_auth_token.h>
36 #include <libgsi/libgsi.h>
37 #include <log/log.h>
38 #include <utils/String16.h>
39 
40 #include <aidl/android/hardware/security/keymint/HardwareAuthToken.h>
41 #include <aidl/android/security/authorization/IKeystoreAuthorization.h>
42 #include <hidl/HidlSupport.h>
43 
44 using android::sp;
45 using android::hardware::Return;
46 using android::hardware::gatekeeper::V1_0::GatekeeperResponse;
47 using android::hardware::gatekeeper::V1_0::GatekeeperStatusCode;
48 
49 using AidlGatekeeperEnrollResp = aidl::android::hardware::gatekeeper::GatekeeperEnrollResponse;
50 using AidlGatekeeperVerifyResp = aidl::android::hardware::gatekeeper::GatekeeperVerifyResponse;
51 
52 using GKResponseCode = ::android::service::gatekeeper::ResponseCode;
53 using ::aidl::android::hardware::security::keymint::HardwareAuthenticatorType;
54 using ::aidl::android::hardware::security::keymint::HardwareAuthToken;
55 using ::aidl::android::hardware::security::keymint::km_utils::authToken2AidlVec;
56 using ::aidl::android::security::authorization::IKeystoreAuthorization;
57 
58 namespace android {
59 
60 static const String16 KEYGUARD_PERMISSION("android.permission.ACCESS_KEYGUARD_SECURE_STORAGE");
61 static const String16 DUMP_PERMISSION("android.permission.DUMP");
62 constexpr const char gatekeeperServiceName[] = "android.hardware.gatekeeper.IGatekeeper/default";
63 
GateKeeperProxy()64 GateKeeperProxy::GateKeeperProxy() {
65     clear_state_if_needed_done = false;
66     if (AServiceManager_isDeclared(gatekeeperServiceName)) {
67         ::ndk::SpAIBinder ks2Binder(AServiceManager_waitForService(gatekeeperServiceName));
68         aidl_hw_device = AidlIGatekeeper::fromBinder(ks2Binder);
69     }
70     if (!aidl_hw_device) {
71         hw_device = IGatekeeper::getService();
72     }
73     is_running_gsi = android::base::GetBoolProperty(android::gsi::kGsiBootedProp, false);
74 
75     if (!aidl_hw_device && !hw_device) {
76         LOG(ERROR) << "Could not find Gatekeeper device, which makes me very sad.";
77     }
78 }
79 
store_sid(uint32_t userId,uint64_t sid)80 void GateKeeperProxy::store_sid(uint32_t userId, uint64_t sid) {
81     char filename[21];
82     snprintf(filename, sizeof(filename), "%u", userId);
83     int fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR);
84     if (fd < 0) {
85         ALOGE("could not open file: %s: %s", filename, strerror(errno));
86         return;
87     }
88     write(fd, &sid, sizeof(sid));
89     close(fd);
90 }
91 
clear_state_if_needed()92 void GateKeeperProxy::clear_state_if_needed() {
93     if (clear_state_if_needed_done) {
94         return;
95     }
96 
97     if (mark_cold_boot() && !is_running_gsi) {
98         ALOGI("cold boot: clearing state");
99         if (aidl_hw_device) {
100             aidl_hw_device->deleteAllUsers();
101         } else if (hw_device) {
102             hw_device->deleteAllUsers([](const GatekeeperResponse&) {});
103         }
104     }
105 
106     clear_state_if_needed_done = true;
107 }
108 
mark_cold_boot()109 bool GateKeeperProxy::mark_cold_boot() {
110     const char* filename = ".coldboot";
111     if (access(filename, F_OK) == -1) {
112         int fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR);
113         if (fd < 0) {
114             ALOGE("could not open file: %s : %s", filename, strerror(errno));
115             return false;
116         }
117         close(fd);
118         return true;
119     }
120     return false;
121 }
122 
maybe_store_sid(uint32_t userId,uint64_t sid)123 void GateKeeperProxy::maybe_store_sid(uint32_t userId, uint64_t sid) {
124     char filename[21];
125     snprintf(filename, sizeof(filename), "%u", userId);
126     if (access(filename, F_OK) == -1) {
127         store_sid(userId, sid);
128     }
129 }
130 
read_sid(uint32_t userId)131 uint64_t GateKeeperProxy::read_sid(uint32_t userId) {
132     char filename[21];
133     uint64_t sid;
134     snprintf(filename, sizeof(filename), "%u", userId);
135     int fd = open(filename, O_RDONLY);
136     if (fd < 0) return 0;
137     read(fd, &sid, sizeof(sid));
138     close(fd);
139     return sid;
140 }
141 
clear_sid(uint32_t userId)142 void GateKeeperProxy::clear_sid(uint32_t userId) {
143     char filename[21];
144     snprintf(filename, sizeof(filename), "%u", userId);
145     if (remove(filename) < 0 && errno != ENOENT) {
146         ALOGE("%s: could not remove file [%s], attempting 0 write", __func__, strerror(errno));
147         store_sid(userId, 0);
148     }
149 }
150 
adjust_userId(uint32_t userId,uint32_t * hw_userId)151 Status GateKeeperProxy::adjust_userId(uint32_t userId, uint32_t* hw_userId) {
152     static constexpr uint32_t kGsiOffset = 1000000;
153     if (userId >= kGsiOffset) {
154         return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
155     }
156 
157     if ((aidl_hw_device == nullptr) && (hw_device == nullptr)) {
158         return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
159     }
160 
161     if (is_running_gsi) {
162         *hw_userId = userId + kGsiOffset;
163         return Status::ok();
164     }
165     *hw_userId = userId;
166     return Status::ok();
167 }
168 
169 #define GK_ERROR *gkResponse = GKResponse::error(), Status::ok()
170 
enroll(int32_t userId,const std::optional<std::vector<uint8_t>> & currentPasswordHandle,const std::optional<std::vector<uint8_t>> & currentPassword,const std::vector<uint8_t> & desiredPassword,GKResponse * gkResponse)171 Status GateKeeperProxy::enroll(int32_t userId,
172                                const std::optional<std::vector<uint8_t>>& currentPasswordHandle,
173                                const std::optional<std::vector<uint8_t>>& currentPassword,
174                                const std::vector<uint8_t>& desiredPassword,
175                                GKResponse* gkResponse) {
176     IPCThreadState* ipc = IPCThreadState::self();
177     const int calling_pid = ipc->getCallingPid();
178     const int calling_uid = ipc->getCallingUid();
179     if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
180         return GK_ERROR;
181     }
182 
183     // Make sure to clear any state from before factory reset as soon as a credential is
184     // enrolled (which may happen during device setup).
185     clear_state_if_needed();
186 
187     // need a desired password to enroll
188     if (desiredPassword.size() == 0) return GK_ERROR;
189 
190     if (!aidl_hw_device && !hw_device) {
191         LOG(ERROR) << "has no HAL to talk to";
192         return GK_ERROR;
193     }
194 
195     android::hardware::hidl_vec<uint8_t> curPwdHandle;
196     android::hardware::hidl_vec<uint8_t> curPwd;
197 
198     if (currentPasswordHandle && currentPassword) {
199         if (hw_device) {
200             // Hidl Implementations expects passwordHandle to be in
201             // gatekeeper::password_handle_t format.
202             if (currentPasswordHandle->size() != sizeof(gatekeeper::password_handle_t)) {
203                 LOG(INFO) << "Password handle has wrong length";
204                 return GK_ERROR;
205             }
206         }
207         curPwdHandle.setToExternal(const_cast<uint8_t*>(currentPasswordHandle->data()),
208                                    currentPasswordHandle->size());
209         curPwd.setToExternal(const_cast<uint8_t*>(currentPassword->data()),
210                              currentPassword->size());
211     }
212 
213     android::hardware::hidl_vec<uint8_t> newPwd;
214     newPwd.setToExternal(const_cast<uint8_t*>(desiredPassword.data()), desiredPassword.size());
215 
216     uint32_t hw_userId = 0;
217     Status result = adjust_userId(userId, &hw_userId);
218     if (!result.isOk()) {
219         return result;
220     }
221 
222     uint64_t secureUserId = 0;
223     if (aidl_hw_device) {
224         // AIDL gatekeeper service
225         AidlGatekeeperEnrollResp rsp;
226         auto result = aidl_hw_device->enroll(hw_userId, curPwdHandle, curPwd, newPwd, &rsp);
227         if (!result.isOk()) {
228             LOG(ERROR) << "enroll transaction failed";
229             return GK_ERROR;
230         }
231         if (rsp.statusCode >= AidlIGatekeeper::STATUS_OK) {
232             *gkResponse = GKResponse::ok({rsp.data.begin(), rsp.data.end()});
233             secureUserId = static_cast<uint64_t>(rsp.secureUserId);
234         } else if (rsp.statusCode == AidlIGatekeeper::ERROR_RETRY_TIMEOUT && rsp.timeoutMs > 0) {
235             *gkResponse = GKResponse::retry(rsp.timeoutMs);
236         } else {
237             *gkResponse = GKResponse::error();
238         }
239     } else if (hw_device) {
240         // HIDL gatekeeper service
241         Return<void> hwRes = hw_device->enroll(
242                 hw_userId, curPwdHandle, curPwd, newPwd,
243                 [&gkResponse](const GatekeeperResponse& rsp) {
244                     if (rsp.code >= GatekeeperStatusCode::STATUS_OK) {
245                         *gkResponse = GKResponse::ok({rsp.data.begin(), rsp.data.end()});
246                     } else if (rsp.code == GatekeeperStatusCode::ERROR_RETRY_TIMEOUT &&
247                                rsp.timeout > 0) {
248                         *gkResponse = GKResponse::retry(rsp.timeout);
249                     } else {
250                         *gkResponse = GKResponse::error();
251                     }
252                 });
253         if (!hwRes.isOk()) {
254             LOG(ERROR) << "enroll transaction failed";
255             return GK_ERROR;
256         }
257         if (gkResponse->response_code() == GKResponseCode::OK) {
258             if (gkResponse->payload().size() != sizeof(gatekeeper::password_handle_t)) {
259                 LOG(ERROR) << "HAL returned password handle of invalid length "
260                            << gkResponse->payload().size();
261                 return GK_ERROR;
262             }
263 
264             const gatekeeper::password_handle_t* handle =
265                     reinterpret_cast<const gatekeeper::password_handle_t*>(
266                             gkResponse->payload().data());
267             secureUserId = handle->user_id;
268         }
269     }
270 
271     if (gkResponse->response_code() == GKResponseCode::OK && !gkResponse->should_reenroll()) {
272         store_sid(userId, secureUserId);
273 
274         GKResponse verifyResponse;
275         // immediately verify this password so we don't ask the user to enter it again
276         // if they just created it.
277         auto status = verify(userId, gkResponse->payload(), desiredPassword, &verifyResponse);
278         if (!status.isOk() || verifyResponse.response_code() != GKResponseCode::OK) {
279             LOG(ERROR) << "Failed to verify password after enrolling";
280         }
281     }
282 
283     return Status::ok();
284 }
285 
verify(int32_t userId,const::std::vector<uint8_t> & enrolledPasswordHandle,const::std::vector<uint8_t> & providedPassword,GKResponse * gkResponse)286 Status GateKeeperProxy::verify(int32_t userId, const ::std::vector<uint8_t>& enrolledPasswordHandle,
287                                const ::std::vector<uint8_t>& providedPassword,
288                                GKResponse* gkResponse) {
289     return verifyChallenge(userId, 0 /* challenge */, enrolledPasswordHandle, providedPassword,
290                            gkResponse);
291 }
292 
verifyChallenge(int32_t userId,int64_t challenge,const std::vector<uint8_t> & enrolledPasswordHandle,const std::vector<uint8_t> & providedPassword,GKResponse * gkResponse)293 Status GateKeeperProxy::verifyChallenge(int32_t userId, int64_t challenge,
294                                         const std::vector<uint8_t>& enrolledPasswordHandle,
295                                         const std::vector<uint8_t>& providedPassword,
296                                         GKResponse* gkResponse) {
297     IPCThreadState* ipc = IPCThreadState::self();
298     const int calling_pid = ipc->getCallingPid();
299     const int calling_uid = ipc->getCallingUid();
300     if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
301         return GK_ERROR;
302     }
303 
304     // can't verify if we're missing either param
305     if (enrolledPasswordHandle.size() == 0 || providedPassword.size() == 0) return GK_ERROR;
306 
307     if (!aidl_hw_device && !hw_device) {
308         LOG(ERROR) << "has no HAL to talk to";
309         return GK_ERROR;
310     }
311 
312     if (hw_device) {
313         // Hidl Implementations expects passwordHandle to be in gatekeeper::password_handle_t
314         if (enrolledPasswordHandle.size() != sizeof(gatekeeper::password_handle_t)) {
315             LOG(INFO) << "Password handle has wrong length";
316             return GK_ERROR;
317         }
318     }
319 
320     uint32_t hw_userId = 0;
321     Status result = adjust_userId(userId, &hw_userId);
322     if (!result.isOk()) {
323         return result;
324     }
325 
326     android::hardware::hidl_vec<uint8_t> curPwdHandle;
327     curPwdHandle.setToExternal(const_cast<uint8_t*>(enrolledPasswordHandle.data()),
328                                enrolledPasswordHandle.size());
329     android::hardware::hidl_vec<uint8_t> enteredPwd;
330     enteredPwd.setToExternal(const_cast<uint8_t*>(providedPassword.data()),
331                              providedPassword.size());
332 
333     uint64_t secureUserId = 0;
334     if (aidl_hw_device) {
335         // AIDL gatekeeper service
336         AidlGatekeeperVerifyResp rsp;
337         auto result = aidl_hw_device->verify(hw_userId, challenge, curPwdHandle, enteredPwd, &rsp);
338         if (!result.isOk()) {
339             LOG(ERROR) << "verify transaction failed";
340             return GK_ERROR;
341         }
342         if (rsp.statusCode >= AidlIGatekeeper::STATUS_OK) {
343             secureUserId = rsp.hardwareAuthToken.userId;
344             // Serialize HardwareAuthToken to a vector as hw_auth_token_t.
345             *gkResponse = GKResponse::ok(
346                     authToken2AidlVec(rsp.hardwareAuthToken),
347                     rsp.statusCode == AidlIGatekeeper::STATUS_REENROLL /* reenroll */);
348         } else if (rsp.statusCode == AidlIGatekeeper::ERROR_RETRY_TIMEOUT) {
349             *gkResponse = GKResponse::retry(rsp.timeoutMs);
350         } else {
351             *gkResponse = GKResponse::error();
352         }
353     } else if (hw_device) {
354         // HIDL gatekeeper service
355         Return<void> hwRes = hw_device->verify(
356                 hw_userId, challenge, curPwdHandle, enteredPwd,
357                 [&gkResponse](const GatekeeperResponse& rsp) {
358                     if (rsp.code >= GatekeeperStatusCode::STATUS_OK) {
359                         *gkResponse = GKResponse::ok(
360                                 {rsp.data.begin(), rsp.data.end()},
361                                 rsp.code == GatekeeperStatusCode::STATUS_REENROLL /* reenroll */);
362                     } else if (rsp.code == GatekeeperStatusCode::ERROR_RETRY_TIMEOUT) {
363                         *gkResponse = GKResponse::retry(rsp.timeout);
364                     } else {
365                         *gkResponse = GKResponse::error();
366                     }
367                 });
368 
369         if (!hwRes.isOk()) {
370             LOG(ERROR) << "verify transaction failed";
371             return GK_ERROR;
372         }
373         const gatekeeper::password_handle_t* handle =
374                 reinterpret_cast<const gatekeeper::password_handle_t*>(
375                         enrolledPasswordHandle.data());
376         secureUserId = handle->user_id;
377     }
378 
379     if (gkResponse->response_code() == GKResponseCode::OK) {
380         if (gkResponse->payload().size() != 0) {
381             // try to connect to IKeystoreAuthorization AIDL service first.
382             AIBinder* authzAIBinder = AServiceManager_getService("android.security.authorization");
383             ::ndk::SpAIBinder authzBinder(authzAIBinder);
384             auto authzService = IKeystoreAuthorization::fromBinder(authzBinder);
385             if (authzService) {
386                 if (gkResponse->payload().size() != sizeof(hw_auth_token_t)) {
387                     LOG(ERROR) << "Incorrect size of AuthToken payload.";
388                     return GK_ERROR;
389                 }
390 
391                 const hw_auth_token_t* hwAuthToken =
392                         reinterpret_cast<const hw_auth_token_t*>(gkResponse->payload().data());
393                 HardwareAuthToken authToken;
394 
395                 authToken.timestamp.milliSeconds = betoh64(hwAuthToken->timestamp);
396                 authToken.challenge = hwAuthToken->challenge;
397                 authToken.userId = hwAuthToken->user_id;
398                 authToken.authenticatorId = hwAuthToken->authenticator_id;
399                 authToken.authenticatorType = static_cast<HardwareAuthenticatorType>(
400                         betoh32(hwAuthToken->authenticator_type));
401                 authToken.mac.assign(&hwAuthToken->hmac[0], &hwAuthToken->hmac[32]);
402                 auto result = authzService->addAuthToken(authToken);
403                 if (!result.isOk()) {
404                     LOG(ERROR) << "Failure in sending AuthToken to AuthorizationService.";
405                     return GK_ERROR;
406                 }
407             } else {
408                 LOG(ERROR) << "Cannot deliver auth token. Unable to communicate with "
409                               "Keystore.";
410                 return GK_ERROR;
411             }
412         }
413 
414         maybe_store_sid(userId, secureUserId);
415     }
416 
417     return Status::ok();
418 }
419 
getSecureUserId(int32_t userId,int64_t * sid)420 Status GateKeeperProxy::getSecureUserId(int32_t userId, int64_t* sid) {
421     *sid = read_sid(userId);
422     return Status::ok();
423 }
424 
clearSecureUserId(int32_t userId)425 Status GateKeeperProxy::clearSecureUserId(int32_t userId) {
426     IPCThreadState* ipc = IPCThreadState::self();
427     const int calling_pid = ipc->getCallingPid();
428     const int calling_uid = ipc->getCallingUid();
429     if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
430         ALOGE("%s: permission denied for [%d:%d]", __func__, calling_pid, calling_uid);
431         return Status::ok();
432     }
433     clear_sid(userId);
434 
435     uint32_t hw_userId = 0;
436     Status result = adjust_userId(userId, &hw_userId);
437     if (!result.isOk()) {
438         return result;
439     }
440 
441     if (aidl_hw_device) {
442         aidl_hw_device->deleteUser(hw_userId);
443     } else if (hw_device) {
444         hw_device->deleteUser(hw_userId, [](const GatekeeperResponse&) {});
445     }
446     return Status::ok();
447 }
448 
reportDeviceSetupComplete()449 Status GateKeeperProxy::reportDeviceSetupComplete() {
450     IPCThreadState* ipc = IPCThreadState::self();
451     const int calling_pid = ipc->getCallingPid();
452     const int calling_uid = ipc->getCallingUid();
453     if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
454         ALOGE("%s: permission denied for [%d:%d]", __func__, calling_pid, calling_uid);
455         return Status::ok();
456     }
457 
458     clear_state_if_needed();
459     return Status::ok();
460 }
461 
dump(int fd,const Vector<String16> &)462 status_t GateKeeperProxy::dump(int fd, const Vector<String16>&) {
463     IPCThreadState* ipc = IPCThreadState::self();
464     const int pid = ipc->getCallingPid();
465     const int uid = ipc->getCallingUid();
466     if (!PermissionCache::checkPermission(DUMP_PERMISSION, pid, uid)) {
467         return PERMISSION_DENIED;
468     }
469 
470     if (aidl_hw_device == nullptr && hw_device == nullptr) {
471         const char* result = "Device not available";
472         write(fd, result, strlen(result) + 1);
473     } else {
474         const char* result = "OK";
475         write(fd, result, strlen(result) + 1);
476     }
477 
478     return OK;
479 }
480 }  // namespace android
481