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 <stdint.h>
23 #include <inttypes.h>
24 #include <fcntl.h>
25 #include <unistd.h>
26 
27 #include <cutils/log.h>
28 #include <utils/Log.h>
29 
30 #include <binder/IPCThreadState.h>
31 #include <binder/IServiceManager.h>
32 #include <binder/PermissionCache.h>
33 #include <utils/String16.h>
34 #include <utils/Log.h>
35 
36 #include <keystore/IKeystoreService.h>
37 #include <keystore/keystore.h> // For error code
38 #include <gatekeeper/password_handle.h> // for password_handle_t
39 #include <hardware/gatekeeper.h>
40 #include <hardware/hw_auth_token.h>
41 
42 #include "SoftGateKeeperDevice.h"
43 #include "IUserManager.h"
44 
45 namespace android {
46 
47 static const String16 KEYGUARD_PERMISSION("android.permission.ACCESS_KEYGUARD_SECURE_STORAGE");
48 static const String16 DUMP_PERMISSION("android.permission.DUMP");
49 
50 class GateKeeperProxy : public BnGateKeeperService {
51 public:
GateKeeperProxy()52     GateKeeperProxy() {
53         int ret = hw_get_module_by_class(GATEKEEPER_HARDWARE_MODULE_ID, NULL, &module);
54         device = NULL;
55 
56         if (ret < 0) {
57             ALOGW("falling back to software GateKeeper");
58             soft_device.reset(new SoftGateKeeperDevice());
59         } else {
60             ret = gatekeeper_open(module, &device);
61             if (ret < 0)
62                 LOG_ALWAYS_FATAL_IF(ret < 0, "Unable to open GateKeeper HAL");
63         }
64 
65         if (mark_cold_boot()) {
66             ALOGI("cold boot: clearing state");
67             if (device != NULL && device->delete_all_users != NULL) {
68                 device->delete_all_users(device);
69             }
70         }
71     }
72 
~GateKeeperProxy()73     virtual ~GateKeeperProxy() {
74         if (device) gatekeeper_close(device);
75     }
76 
store_sid(uint32_t uid,uint64_t sid)77     void store_sid(uint32_t uid, uint64_t sid) {
78         char filename[21];
79         sprintf(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 
mark_cold_boot()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 
maybe_store_sid(uint32_t uid,uint64_t sid)103     void maybe_store_sid(uint32_t uid, uint64_t sid) {
104         char filename[21];
105         sprintf(filename, "%u", uid);
106         if (access(filename, F_OK) == -1) {
107             store_sid(uid, sid);
108         }
109     }
110 
read_sid(uint32_t uid)111     uint64_t read_sid(uint32_t uid) {
112         char filename[21];
113         uint64_t sid;
114         sprintf(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 
clear_sid(uint32_t uid)122     void clear_sid(uint32_t uid) {
123         char filename[21];
124         sprintf(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 
enroll(uint32_t uid,const uint8_t * current_password_handle,uint32_t current_password_handle_length,const uint8_t * current_password,uint32_t current_password_length,const uint8_t * desired_password,uint32_t desired_password_length,uint8_t ** enrolled_password_handle,uint32_t * enrolled_password_handle_length)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 (device) {
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             ret = device->enroll(device, uid, current_password_handle, current_password_handle_length,
161                     current_password, current_password_length,
162                     desired_password, desired_password_length,
163                     enrolled_password_handle, enrolled_password_handle_length);
164         } else {
165             ret = soft_device->enroll(uid,
166                     current_password_handle, current_password_handle_length,
167                     current_password, current_password_length,
168                     desired_password, desired_password_length,
169                     enrolled_password_handle, enrolled_password_handle_length);
170         }
171 
172         if (ret == 0) {
173             gatekeeper::password_handle_t *handle =
174                     reinterpret_cast<gatekeeper::password_handle_t *>(*enrolled_password_handle);
175             store_sid(uid, handle->user_id);
176             bool rr;
177 
178             // immediately verify this password so we don't ask the user to enter it again
179             // if they just created it.
180             verify(uid, *enrolled_password_handle, sizeof(password_handle_t), desired_password,
181                     desired_password_length, &rr);
182         }
183 
184         return ret;
185     }
186 
verify(uint32_t uid,const uint8_t * enrolled_password_handle,uint32_t enrolled_password_handle_length,const uint8_t * provided_password,uint32_t provided_password_length,bool * request_reenroll)187     virtual int verify(uint32_t uid,
188             const uint8_t *enrolled_password_handle, uint32_t enrolled_password_handle_length,
189             const uint8_t *provided_password, uint32_t provided_password_length, bool *request_reenroll) {
190         uint8_t *auth_token;
191         uint32_t auth_token_length;
192         return verifyChallenge(uid, 0, enrolled_password_handle, enrolled_password_handle_length,
193                 provided_password, provided_password_length,
194                 &auth_token, &auth_token_length, request_reenroll);
195     }
196 
verifyChallenge(uint32_t uid,uint64_t challenge,const uint8_t * enrolled_password_handle,uint32_t enrolled_password_handle_length,const uint8_t * provided_password,uint32_t provided_password_length,uint8_t ** auth_token,uint32_t * auth_token_length,bool * request_reenroll)197     virtual int verifyChallenge(uint32_t uid, uint64_t challenge,
198             const uint8_t *enrolled_password_handle, uint32_t enrolled_password_handle_length,
199             const uint8_t *provided_password, uint32_t provided_password_length,
200             uint8_t **auth_token, uint32_t *auth_token_length, bool *request_reenroll) {
201         IPCThreadState* ipc = IPCThreadState::self();
202         const int calling_pid = ipc->getCallingPid();
203         const int calling_uid = ipc->getCallingUid();
204         if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
205             return PERMISSION_DENIED;
206         }
207 
208         // can't verify if we're missing either param
209         if ((enrolled_password_handle_length | provided_password_length) == 0)
210             return -EINVAL;
211 
212         int ret;
213         if (device) {
214             const gatekeeper::password_handle_t *handle =
215                     reinterpret_cast<const gatekeeper::password_handle_t *>(enrolled_password_handle);
216             // handle version 0 does not have hardware backed flag, and thus cannot be upgraded to
217             // a HAL if there was none before
218             if (handle->version == 0 || handle->hardware_backed) {
219                 ret = device->verify(device, uid, challenge,
220                     enrolled_password_handle, enrolled_password_handle_length,
221                     provided_password, provided_password_length, auth_token, auth_token_length,
222                     request_reenroll);
223             } else {
224                 // upgrade scenario, a HAL has been added to this device where there was none before
225                 SoftGateKeeperDevice soft_dev;
226                 ret = soft_dev.verify(uid, challenge,
227                     enrolled_password_handle, enrolled_password_handle_length,
228                     provided_password, provided_password_length, auth_token, auth_token_length,
229                     request_reenroll);
230 
231                 if (ret == 0) {
232                     // success! re-enroll with HAL
233                     *request_reenroll = true;
234                 }
235             }
236         } else {
237             ret = soft_device->verify(uid, challenge,
238                 enrolled_password_handle, enrolled_password_handle_length,
239                 provided_password, provided_password_length, auth_token, auth_token_length,
240                 request_reenroll);
241         }
242 
243         if (ret == 0 && *auth_token != NULL && *auth_token_length > 0) {
244             // TODO: cache service?
245             sp<IServiceManager> sm = defaultServiceManager();
246             sp<IBinder> binder = sm->getService(String16("android.security.keystore"));
247             sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
248             if (service != NULL) {
249                 status_t ret = service->addAuthToken(*auth_token, *auth_token_length);
250                 if (ret != ResponseCode::NO_ERROR) {
251                     ALOGE("Falure sending auth token to KeyStore: %d", ret);
252                 }
253             } else {
254                 ALOGE("Unable to communicate with KeyStore");
255             }
256         }
257 
258         if (ret == 0) {
259             maybe_store_sid(uid, reinterpret_cast<const gatekeeper::password_handle_t *>(
260                         enrolled_password_handle)->user_id);
261         }
262 
263         return ret;
264     }
265 
getSecureUserId(uint32_t uid)266     virtual uint64_t getSecureUserId(uint32_t uid) {
267         uint64_t sid = read_sid(uid);
268          if (sid == 0) {
269             // might be a work profile, look up the parent
270             sp<IServiceManager> sm = defaultServiceManager();
271             sp<IBinder> binder = sm->getService(String16("user"));
272             sp<IUserManager> um = interface_cast<IUserManager>(binder);
273             int32_t parent = um->getCredentialOwnerProfile(uid);
274             if (parent < 0) {
275                 return 0;
276             } else if (parent != (int32_t) uid) {
277                 return read_sid(parent);
278             }
279         }
280         return sid;
281 
282     }
283 
clearSecureUserId(uint32_t uid)284     virtual void clearSecureUserId(uint32_t uid) {
285         IPCThreadState* ipc = IPCThreadState::self();
286         const int calling_pid = ipc->getCallingPid();
287         const int calling_uid = ipc->getCallingUid();
288         if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
289             ALOGE("%s: permission denied for [%d:%d]", __func__, calling_pid, calling_uid);
290             return;
291         }
292         clear_sid(uid);
293 
294         if (device != NULL && device->delete_user != NULL) {
295             device->delete_user(device, uid);
296         }
297     }
298 
dump(int fd,const Vector<String16> &)299     virtual status_t dump(int fd, const Vector<String16> &) {
300         IPCThreadState* ipc = IPCThreadState::self();
301         const int pid = ipc->getCallingPid();
302         const int uid = ipc->getCallingUid();
303         if (!PermissionCache::checkPermission(DUMP_PERMISSION, pid, uid)) {
304             return PERMISSION_DENIED;
305         }
306 
307         if (device == NULL) {
308             const char *result = "Device not available";
309             write(fd, result, strlen(result) + 1);
310         } else {
311             const char *result = "OK";
312             write(fd, result, strlen(result) + 1);
313         }
314 
315         return NO_ERROR;
316     }
317 
318 private:
319     gatekeeper_device_t *device;
320     UniquePtr<SoftGateKeeperDevice> soft_device;
321     const hw_module_t *module;
322 };
323 }// namespace android
324 
main(int argc,char * argv[])325 int main(int argc, char* argv[]) {
326     ALOGI("Starting gatekeeperd...");
327     if (argc < 2) {
328         ALOGE("A directory must be specified!");
329         return 1;
330     }
331     if (chdir(argv[1]) == -1) {
332         ALOGE("chdir: %s: %s", argv[1], strerror(errno));
333         return 1;
334     }
335 
336     android::sp<android::IServiceManager> sm = android::defaultServiceManager();
337     android::sp<android::GateKeeperProxy> proxy = new android::GateKeeperProxy();
338     android::status_t ret = sm->addService(
339             android::String16("android.service.gatekeeper.IGateKeeperService"), proxy);
340     if (ret != android::OK) {
341         ALOGE("Couldn't register binder service!");
342         return -1;
343     }
344 
345     /*
346      * We're the only thread in existence, so we're just going to process
347      * Binder transaction as a single-threaded program.
348      */
349     android::IPCThreadState::self()->joinThreadPool();
350     return 0;
351 }
352