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