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