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