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