1 /*
2  * Copyright (C) 2016 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 "gatekeeper_hidl_hal_test"
18 
19 #include <algorithm>
20 #include <cmath>
21 #include <string>
22 #include <vector>
23 
24 #include <inttypes.h>
25 #include <unistd.h>
26 
27 #include <gtest/gtest.h>
28 #include <hardware/hw_auth_token.h>
29 #include <hidl/GtestPrinter.h>
30 #include <hidl/ServiceManagement.h>
31 
32 #include <android/log.h>
33 #include <android/hardware/gatekeeper/1.0/IGatekeeper.h>
34 #include <android/hardware/gatekeeper/1.0/types.h>
35 
36 #include <log/log.h>
37 
38 using ::android::hardware::hidl_string;
39 using ::android::hardware::hidl_vec;
40 using ::android::hardware::gatekeeper::V1_0::IGatekeeper;
41 using ::android::hardware::gatekeeper::V1_0::GatekeeperResponse;
42 using ::android::hardware::gatekeeper::V1_0::GatekeeperStatusCode;
43 using ::android::hardware::Return;
44 using ::android::hardware::Void;
45 using ::android::sp;
46 
47 struct GatekeeperRequest {
48   uint32_t uid;
49   uint64_t challenge;
50   hidl_vec<uint8_t> curPwdHandle;
51   hidl_vec<uint8_t> curPwd;
52   hidl_vec<uint8_t> newPwd;
GatekeeperRequestGatekeeperRequest53   GatekeeperRequest() : uid(0), challenge(0) {}
54 };
55 
56 // ASSERT_* macros generate return "void" internally
57 // we have to use EXPECT_* if we return anything but "void"
toAuthToken(GatekeeperResponse & rsp)58 static const hw_auth_token_t *toAuthToken(GatekeeperResponse &rsp) {
59   const hw_auth_token_t *auth_token =
60       reinterpret_cast<hw_auth_token_t *>(rsp.data.data());
61   const size_t auth_token_size = rsp.data.size();
62 
63   EXPECT_NE(nullptr, auth_token);
64   EXPECT_EQ(sizeof(hw_auth_token_t), auth_token_size);
65 
66   if (auth_token != nullptr && auth_token_size >= sizeof(*auth_token)) {
67     // these are in network order: translate to host
68     uint32_t auth_type = ntohl(auth_token->authenticator_type);
69     uint64_t auth_tstamp = ntohq(auth_token->timestamp);
70 
71     EXPECT_EQ(HW_AUTH_PASSWORD, auth_type);
72     EXPECT_NE(UINT64_C(~0), auth_tstamp);
73     EXPECT_EQ(HW_AUTH_TOKEN_VERSION, auth_token->version);
74     //        EXPECT_NE(UINT64_C(0), auth_token->authenticator_id);
75     ALOGI("Authenticator ID: %016" PRIX64, auth_token->authenticator_id);
76     EXPECT_NE(UINT32_C(0), auth_token->user_id);
77   }
78   return auth_token;
79 }
80 
81 // The main test class for Gatekeeper HIDL HAL.
82 class GatekeeperHidlTest : public ::testing::TestWithParam<std::string> {
83  protected:
setUid(uint32_t uid)84   void setUid(uint32_t uid) { uid_ = uid; }
85 
doEnroll(GatekeeperRequest & req,GatekeeperResponse & rsp)86   void doEnroll(GatekeeperRequest &req, GatekeeperResponse &rsp) {
87     while (true) {
88       auto ret = gatekeeper_->enroll(
89           uid_, req.curPwdHandle, req.curPwd, req.newPwd,
90           [&rsp](const GatekeeperResponse &cbRsp) { rsp = cbRsp; });
91       ASSERT_TRUE(ret.isOk());
92       if (rsp.code != GatekeeperStatusCode::ERROR_RETRY_TIMEOUT) break;
93       ALOGI("%s: got retry code; retrying in 1 sec", __func__);
94       sleep(1);
95     }
96   }
97 
doVerify(GatekeeperRequest & req,GatekeeperResponse & rsp)98   void doVerify(GatekeeperRequest &req, GatekeeperResponse &rsp) {
99     while (true) {
100       auto ret = gatekeeper_->verify(
101           uid_, req.challenge, req.curPwdHandle, req.newPwd,
102           [&rsp](const GatekeeperResponse &cb_rsp) { rsp = cb_rsp; });
103       ASSERT_TRUE(ret.isOk());
104       if (rsp.code != GatekeeperStatusCode::ERROR_RETRY_TIMEOUT) break;
105       ALOGI("%s: got retry code; retrying in 1 sec", __func__);
106       sleep(1);
107     }
108   }
109 
doDeleteUser(GatekeeperResponse & rsp)110   void doDeleteUser(GatekeeperResponse &rsp) {
111     while (true) {
112       auto ret = gatekeeper_->deleteUser(
113           uid_, [&rsp](const GatekeeperResponse &cb_rsp) { rsp = cb_rsp; });
114       ASSERT_TRUE(ret.isOk());
115       if (rsp.code != GatekeeperStatusCode::ERROR_RETRY_TIMEOUT) break;
116       ALOGI("%s: got retry code; retrying in 1 sec", __func__);
117       sleep(1);
118     }
119   }
120 
doDeleteAllUsers(GatekeeperResponse & rsp)121   void doDeleteAllUsers(GatekeeperResponse &rsp) {
122     while (true) {
123       auto ret = gatekeeper_->deleteAllUsers(
124           [&rsp](const GatekeeperResponse &cb_rsp) { rsp = cb_rsp; });
125       ASSERT_TRUE(ret.isOk());
126       if (rsp.code != GatekeeperStatusCode::ERROR_RETRY_TIMEOUT) break;
127       ALOGI("%s: got retry code; retrying in 1 sec", __func__);
128       sleep(1);
129     }
130   }
131 
generatePassword(hidl_vec<uint8_t> & password,uint8_t seed)132   void generatePassword(hidl_vec<uint8_t> &password, uint8_t seed) {
133     password.resize(16);
134     memset(password.data(), seed, password.size());
135   }
136 
checkEnroll(GatekeeperResponse & rsp,bool expectSuccess)137   void checkEnroll(GatekeeperResponse &rsp, bool expectSuccess) {
138     if (expectSuccess) {
139       EXPECT_EQ(GatekeeperStatusCode::STATUS_OK, rsp.code);
140       EXPECT_NE(nullptr, rsp.data.data());
141       EXPECT_GT(rsp.data.size(), UINT32_C(0));
142     } else {
143       EXPECT_EQ(GatekeeperStatusCode::ERROR_GENERAL_FAILURE, rsp.code);
144       EXPECT_EQ(UINT32_C(0), rsp.data.size());
145     }
146   }
147 
checkVerify(GatekeeperResponse & rsp,uint64_t challenge,bool expectSuccess)148   void checkVerify(GatekeeperResponse &rsp, uint64_t challenge,
149                    bool expectSuccess) {
150     if (expectSuccess) {
151       EXPECT_GE(rsp.code, GatekeeperStatusCode::STATUS_OK);
152       EXPECT_LE(rsp.code, GatekeeperStatusCode::STATUS_REENROLL);
153 
154       const hw_auth_token_t *auth_token = toAuthToken(rsp);
155       ASSERT_NE(nullptr, auth_token);
156       EXPECT_EQ(challenge, auth_token->challenge);
157     } else {
158       EXPECT_EQ(GatekeeperStatusCode::ERROR_GENERAL_FAILURE, rsp.code);
159       EXPECT_EQ(UINT32_C(0), rsp.data.size());
160     }
161   }
162 
enrollNewPassword(hidl_vec<uint8_t> & password,GatekeeperResponse & rsp,bool expectSuccess)163   void enrollNewPassword(hidl_vec<uint8_t> &password, GatekeeperResponse &rsp,
164                          bool expectSuccess) {
165     GatekeeperRequest req;
166     req.newPwd.setToExternal(password.data(), password.size());
167     doEnroll(req, rsp);
168     checkEnroll(rsp, expectSuccess);
169   }
170 
verifyPassword(hidl_vec<uint8_t> & password,hidl_vec<uint8_t> & passwordHandle,uint64_t challenge,GatekeeperResponse & verifyRsp,bool expectSuccess)171   void verifyPassword(hidl_vec<uint8_t> &password,
172                       hidl_vec<uint8_t> &passwordHandle, uint64_t challenge,
173                       GatekeeperResponse &verifyRsp, bool expectSuccess) {
174     GatekeeperRequest verifyReq;
175 
176     // build verify request for the same password (we want it to succeed)
177     verifyReq.newPwd = password;
178     // use enrolled password handle we've got
179     verifyReq.curPwdHandle = passwordHandle;
180     verifyReq.challenge = challenge;
181     doVerify(verifyReq, verifyRsp);
182     checkVerify(verifyRsp, challenge, expectSuccess);
183   }
184 
185  protected:
186   sp<IGatekeeper> gatekeeper_;
187   uint32_t uid_;
188 
189  public:
GatekeeperHidlTest()190   GatekeeperHidlTest() : uid_(0) {}
SetUp()191   virtual void SetUp() override {
192     GatekeeperResponse rsp;
193     gatekeeper_ = IGatekeeper::getService(GetParam());
194     ASSERT_NE(nullptr, gatekeeper_.get());
195     doDeleteAllUsers(rsp);
196   }
197 
TearDown()198   virtual void TearDown() override {
199     GatekeeperResponse rsp;
200     doDeleteAllUsers(rsp);
201   }
202 };
203 
204 /**
205  * Ensure we can enroll new password
206  */
TEST_P(GatekeeperHidlTest,EnrollSuccess)207 TEST_P(GatekeeperHidlTest, EnrollSuccess) {
208   hidl_vec<uint8_t> password;
209   GatekeeperResponse rsp;
210   ALOGI("Testing Enroll (expected success)");
211   generatePassword(password, 0);
212   enrollNewPassword(password, rsp, true);
213   ALOGI("Testing Enroll done");
214 }
215 
216 /**
217  * Ensure we can not enroll empty password
218  */
TEST_P(GatekeeperHidlTest,EnrollNoPassword)219 TEST_P(GatekeeperHidlTest, EnrollNoPassword) {
220   hidl_vec<uint8_t> password;
221   GatekeeperResponse rsp;
222   ALOGI("Testing Enroll (expected failure)");
223   enrollNewPassword(password, rsp, false);
224   ALOGI("Testing Enroll done");
225 }
226 
227 /**
228  * Ensure we can successfully verify previously enrolled password
229  */
TEST_P(GatekeeperHidlTest,VerifySuccess)230 TEST_P(GatekeeperHidlTest, VerifySuccess) {
231   GatekeeperResponse enrollRsp;
232   GatekeeperResponse verifyRsp;
233   hidl_vec<uint8_t> password;
234 
235   ALOGI("Testing Enroll+Verify (expected success)");
236   generatePassword(password, 0);
237   enrollNewPassword(password, enrollRsp, true);
238   verifyPassword(password, enrollRsp.data, 1, verifyRsp, true);
239   ALOGI("Testing Enroll+Verify done");
240 }
241 
242 /**
243  * Ensure we can securely update password (keep the same
244  * secure user_id) if we prove we know old password
245  */
TEST_P(GatekeeperHidlTest,TrustedReenroll)246 TEST_P(GatekeeperHidlTest, TrustedReenroll) {
247   GatekeeperResponse enrollRsp;
248   GatekeeperRequest reenrollReq;
249   GatekeeperResponse reenrollRsp;
250   GatekeeperResponse verifyRsp;
251   GatekeeperResponse reenrollVerifyRsp;
252   hidl_vec<uint8_t> password;
253   hidl_vec<uint8_t> newPassword;
254 
255   generatePassword(password, 0);
256 
257   ALOGI("Testing Trusted Reenroll (expected success)");
258   enrollNewPassword(password, enrollRsp, true);
259   verifyPassword(password, enrollRsp.data, 0, verifyRsp, true);
260   ALOGI("Primary Enroll+Verify done");
261 
262   generatePassword(newPassword, 1);
263   reenrollReq.newPwd.setToExternal(newPassword.data(), newPassword.size());
264   reenrollReq.curPwd.setToExternal(password.data(), password.size());
265   reenrollReq.curPwdHandle.setToExternal(enrollRsp.data.data(),
266                                          enrollRsp.data.size());
267 
268   doEnroll(reenrollReq, reenrollRsp);
269   checkEnroll(reenrollRsp, true);
270   verifyPassword(newPassword, reenrollRsp.data, 0, reenrollVerifyRsp, true);
271   ALOGI("Trusted ReEnroll+Verify done");
272 
273   const hw_auth_token_t *first = toAuthToken(verifyRsp);
274   const hw_auth_token_t *second = toAuthToken(reenrollVerifyRsp);
275   if (first != nullptr && second != nullptr) {
276     EXPECT_EQ(first->user_id, second->user_id);
277   }
278   ALOGI("Testing Trusted Reenroll done");
279 }
280 
281 /**
282  * Ensure we can update password (and get new
283  * secure user_id) if we don't know old password
284  */
TEST_P(GatekeeperHidlTest,UntrustedReenroll)285 TEST_P(GatekeeperHidlTest, UntrustedReenroll) {
286   GatekeeperResponse enrollRsp;
287   GatekeeperResponse reenrollRsp;
288   GatekeeperResponse verifyRsp;
289   GatekeeperResponse reenrollVerifyRsp;
290   hidl_vec<uint8_t> password;
291   hidl_vec<uint8_t> newPassword;
292 
293   ALOGI("Testing Untrusted Reenroll (expected success)");
294   generatePassword(password, 0);
295   enrollNewPassword(password, enrollRsp, true);
296   verifyPassword(password, enrollRsp.data, 0, verifyRsp, true);
297   ALOGI("Primary Enroll+Verify done");
298 
299   generatePassword(newPassword, 1);
300   enrollNewPassword(newPassword, reenrollRsp, true);
301   verifyPassword(newPassword, reenrollRsp.data, 0, reenrollVerifyRsp, true);
302   ALOGI("Untrusted ReEnroll+Verify done");
303 
304   const hw_auth_token_t *first = toAuthToken(verifyRsp);
305   const hw_auth_token_t *second = toAuthToken(reenrollVerifyRsp);
306   if (first != nullptr && second != nullptr) {
307     EXPECT_NE(first->user_id, second->user_id);
308   }
309   ALOGI("Testing Untrusted Reenroll done");
310 }
311 
312 /**
313  * Ensure we dont get successful verify with invalid data
314  */
TEST_P(GatekeeperHidlTest,VerifyNoData)315 TEST_P(GatekeeperHidlTest, VerifyNoData) {
316   hidl_vec<uint8_t> password;
317   hidl_vec<uint8_t> passwordHandle;
318   GatekeeperResponse verifyRsp;
319 
320   ALOGI("Testing Verify (expected failure)");
321   verifyPassword(password, passwordHandle, 0, verifyRsp, false);
322   EXPECT_EQ(GatekeeperStatusCode::ERROR_GENERAL_FAILURE, verifyRsp.code);
323   ALOGI("Testing Verify done");
324 }
325 
326 /**
327  * Ensure we can not verify password after we enrolled it and then deleted user
328  */
TEST_P(GatekeeperHidlTest,DeleteUserTest)329 TEST_P(GatekeeperHidlTest, DeleteUserTest) {
330   hidl_vec<uint8_t> password;
331   GatekeeperResponse enrollRsp;
332   GatekeeperResponse verifyRsp;
333   GatekeeperResponse delRsp;
334   ALOGI("Testing deleteUser (expected success)");
335   setUid(10001);
336   generatePassword(password, 0);
337   enrollNewPassword(password, enrollRsp, true);
338   verifyPassword(password, enrollRsp.data, 0, verifyRsp, true);
339   ALOGI("Enroll+Verify done");
340   doDeleteUser(delRsp);
341   EXPECT_EQ(UINT32_C(0), delRsp.data.size());
342   EXPECT_TRUE(delRsp.code == GatekeeperStatusCode::ERROR_NOT_IMPLEMENTED ||
343               delRsp.code == GatekeeperStatusCode::STATUS_OK);
344   ALOGI("DeleteUser done");
345   if (delRsp.code == GatekeeperStatusCode::STATUS_OK) {
346     verifyPassword(password, enrollRsp.data, 0, verifyRsp, false);
347     EXPECT_EQ(GatekeeperStatusCode::ERROR_GENERAL_FAILURE, verifyRsp.code);
348     ALOGI("Verify after Delete done (must fail)");
349   }
350   ALOGI("Testing deleteUser done: rsp=%" PRIi32, delRsp.code);
351 }
352 
353 /**
354  * Ensure we can not delete a user that does not exist
355  */
TEST_P(GatekeeperHidlTest,DeleteInvalidUserTest)356 TEST_P(GatekeeperHidlTest, DeleteInvalidUserTest) {
357   hidl_vec<uint8_t> password;
358   GatekeeperResponse enrollRsp;
359   GatekeeperResponse verifyRsp;
360   GatekeeperResponse delRsp1;
361   GatekeeperResponse delRsp2;
362   ALOGI("Testing deleteUser (expected failure)");
363   setUid(10002);
364   generatePassword(password, 0);
365   enrollNewPassword(password, enrollRsp, true);
366   verifyPassword(password, enrollRsp.data, 0, verifyRsp, true);
367   ALOGI("Enroll+Verify done");
368 
369   // Delete the user
370   doDeleteUser(delRsp1);
371   EXPECT_EQ(UINT32_C(0), delRsp1.data.size());
372   EXPECT_TRUE(delRsp1.code == GatekeeperStatusCode::ERROR_NOT_IMPLEMENTED ||
373               delRsp1.code == GatekeeperStatusCode::STATUS_OK);
374 
375   // Delete the user again
376   doDeleteUser(delRsp2);
377   EXPECT_EQ(UINT32_C(0), delRsp2.data.size());
378   EXPECT_TRUE(delRsp2.code == GatekeeperStatusCode::ERROR_NOT_IMPLEMENTED ||
379               delRsp2.code == GatekeeperStatusCode::ERROR_GENERAL_FAILURE);
380   ALOGI("DeleteUser done");
381   ALOGI("Testing deleteUser done: rsp=%" PRIi32, delRsp2.code);
382 }
383 
384 /**
385  * Ensure we can not verify passwords after we enrolled them and then deleted
386  * all users
387  */
TEST_P(GatekeeperHidlTest,DeleteAllUsersTest)388 TEST_P(GatekeeperHidlTest, DeleteAllUsersTest) {
389   struct UserData {
390     uint32_t userId;
391     hidl_vec<uint8_t> password;
392     GatekeeperResponse enrollRsp;
393     GatekeeperResponse verifyRsp;
394     UserData(int id) { userId = id; }
395   } users[3]{10001, 10002, 10003};
396   GatekeeperResponse delAllRsp;
397   ALOGI("Testing deleteAllUsers (expected success)");
398 
399   // enroll multiple users
400   for (size_t i = 0; i < sizeof(users) / sizeof(users[0]); ++i) {
401     setUid(users[i].userId);
402     generatePassword(users[i].password, (i % 255) + 1);
403     enrollNewPassword(users[i].password, users[i].enrollRsp, true);
404   }
405   ALOGI("Multiple users enrolled");
406 
407   // verify multiple users
408   for (size_t i = 0; i < sizeof(users) / sizeof(users[0]); ++i) {
409     setUid(users[i].userId);
410     verifyPassword(users[i].password, users[i].enrollRsp.data, 0,
411                    users[i].verifyRsp, true);
412   }
413   ALOGI("Multiple users verified");
414 
415   doDeleteAllUsers(delAllRsp);
416   EXPECT_EQ(UINT32_C(0), delAllRsp.data.size());
417   EXPECT_TRUE(delAllRsp.code == GatekeeperStatusCode::ERROR_NOT_IMPLEMENTED ||
418               delAllRsp.code == GatekeeperStatusCode::STATUS_OK);
419   ALOGI("All users deleted");
420 
421   if (delAllRsp.code == GatekeeperStatusCode::STATUS_OK) {
422     // verify multiple users after they are deleted; all must fail
423     for (size_t i = 0; i < sizeof(users) / sizeof(users[0]); ++i) {
424       setUid(users[i].userId);
425       verifyPassword(users[i].password, users[i].enrollRsp.data, 0,
426                      users[i].verifyRsp, false);
427       EXPECT_EQ(GatekeeperStatusCode::ERROR_GENERAL_FAILURE,
428                 users[i].verifyRsp.code);
429     }
430     ALOGI("Multiple users verified after delete (all must fail)");
431   }
432 
433   ALOGI("Testing deleteAllUsers done: rsp=%" PRIi32, delAllRsp.code);
434 }
435 
436 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(GatekeeperHidlTest);
437 INSTANTIATE_TEST_SUITE_P(
438         PerInstance, GatekeeperHidlTest,
439         testing::ValuesIn(android::hardware::getAllHalInstanceNames(IGatekeeper::descriptor)),
440         android::hardware::PrintInstanceNameToString);
441