1 /*
2 * Copyright (C) 2020 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 #include <aidl/Gtest.h>
17 #include <aidl/Vintf.h>
18
19 #include <aidl/android/hardware/weaver/IWeaver.h>
20 #include <android-base/file.h>
21 #include <android-base/parseint.h>
22 #include <android-base/strings.h>
23 #include <android/binder_manager.h>
24 #include <android/binder_process.h>
25 #include <android/hardware/weaver/1.0/IWeaver.h>
26 #include <hidl/GtestPrinter.h>
27 #include <hidl/ServiceManagement.h>
28
29 #include <limits>
30
31 using ::aidl::android::hardware::weaver::IWeaver;
32 using ::aidl::android::hardware::weaver::WeaverConfig;
33 using ::aidl::android::hardware::weaver::WeaverReadResponse;
34 using ::aidl::android::hardware::weaver::WeaverReadStatus;
35
36 using HidlIWeaver = ::android::hardware::weaver::V1_0::IWeaver;
37 using HidlWeaverConfig = ::android::hardware::weaver::V1_0::WeaverConfig;
38 using HidlWeaverReadStatus = ::android::hardware::weaver::V1_0::WeaverReadStatus;
39 using HidlWeaverReadResponse = ::android::hardware::weaver::V1_0::WeaverReadResponse;
40 using HidlWeaverStatus = ::android::hardware::weaver::V1_0::WeaverStatus;
41
42 const std::string kSlotMapFile = "/metadata/password_slots/slot_map";
43 const std::vector<uint8_t> KEY{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
44 const std::vector<uint8_t> WRONG_KEY{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
45 const std::vector<uint8_t> VALUE{16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
46 const std::vector<uint8_t> OTHER_VALUE{0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 255, 255};
47
48 class WeaverAdapter {
49 public:
~WeaverAdapter()50 virtual ~WeaverAdapter() {}
51 virtual bool isReady() = 0;
52 virtual ::ndk::ScopedAStatus getConfig(WeaverConfig* _aidl_return) = 0;
53 virtual ::ndk::ScopedAStatus read(int32_t in_slotId, const std::vector<uint8_t>& in_key,
54 WeaverReadResponse* _aidl_return) = 0;
55 virtual ::ndk::ScopedAStatus write(int32_t in_slotId, const std::vector<uint8_t>& in_key,
56 const std::vector<uint8_t>& in_value) = 0;
57 };
58
59 class WeaverAidlAdapter : public WeaverAdapter {
60 public:
WeaverAidlAdapter(const std::string & param)61 WeaverAidlAdapter(const std::string& param)
62 : aidl_weaver_(IWeaver::fromBinder(
63 ::ndk::SpAIBinder(AServiceManager_waitForService(param.c_str())))) {}
~WeaverAidlAdapter()64 ~WeaverAidlAdapter() {}
65
isReady()66 bool isReady() { return aidl_weaver_ != nullptr; }
67
getConfig(WeaverConfig * _aidl_return)68 ::ndk::ScopedAStatus getConfig(WeaverConfig* _aidl_return) {
69 return aidl_weaver_->getConfig(_aidl_return);
70 }
71
read(int32_t in_slotId,const std::vector<uint8_t> & in_key,WeaverReadResponse * _aidl_return)72 ::ndk::ScopedAStatus read(int32_t in_slotId, const std::vector<uint8_t>& in_key,
73 WeaverReadResponse* _aidl_return) {
74 return aidl_weaver_->read(in_slotId, in_key, _aidl_return);
75 }
76
write(int32_t in_slotId,const std::vector<uint8_t> & in_key,const std::vector<uint8_t> & in_value)77 ::ndk::ScopedAStatus write(int32_t in_slotId, const std::vector<uint8_t>& in_key,
78 const std::vector<uint8_t>& in_value) {
79 return aidl_weaver_->write(in_slotId, in_key, in_value);
80 }
81
82 private:
83 std::shared_ptr<IWeaver> aidl_weaver_;
84 };
85
86 class WeaverHidlAdapter : public WeaverAdapter {
87 public:
WeaverHidlAdapter(const std::string & param)88 WeaverHidlAdapter(const std::string& param) : hidl_weaver_(HidlIWeaver::getService(param)) {}
~WeaverHidlAdapter()89 ~WeaverHidlAdapter() {}
90
isReady()91 bool isReady() { return hidl_weaver_ != nullptr; }
92
getConfig(WeaverConfig * _aidl_return)93 ::ndk::ScopedAStatus getConfig(WeaverConfig* _aidl_return) {
94 bool callbackCalled = false;
95 HidlWeaverStatus status;
96 HidlWeaverConfig config;
97 auto ret = hidl_weaver_->getConfig([&](HidlWeaverStatus s, HidlWeaverConfig c) {
98 callbackCalled = true;
99 status = s;
100 config = c;
101 });
102 if (!ret.isOk() || !callbackCalled || status != HidlWeaverStatus::OK) {
103 return ::ndk::ScopedAStatus::fromStatus(STATUS_FAILED_TRANSACTION);
104 }
105 _aidl_return->slots = config.slots;
106 _aidl_return->keySize = config.keySize;
107 _aidl_return->valueSize = config.valueSize;
108 return ::ndk::ScopedAStatus::ok();
109 }
110
read(int32_t in_slotId,const std::vector<uint8_t> & in_key,WeaverReadResponse * _aidl_return)111 ::ndk::ScopedAStatus read(int32_t in_slotId, const std::vector<uint8_t>& in_key,
112 WeaverReadResponse* _aidl_return) {
113 bool callbackCalled = false;
114 HidlWeaverReadStatus status;
115 std::vector<uint8_t> value;
116 uint32_t timeout;
117 auto ret = hidl_weaver_->read(in_slotId, in_key,
118 [&](HidlWeaverReadStatus s, HidlWeaverReadResponse r) {
119 callbackCalled = true;
120 status = s;
121 value = r.value;
122 timeout = r.timeout;
123 });
124 if (!ret.isOk() || !callbackCalled) {
125 return ::ndk::ScopedAStatus::fromStatus(STATUS_FAILED_TRANSACTION);
126 }
127 switch (status) {
128 case HidlWeaverReadStatus::OK:
129 _aidl_return->status = WeaverReadStatus::OK;
130 break;
131 case HidlWeaverReadStatus::FAILED:
132 _aidl_return->status = WeaverReadStatus::FAILED;
133 break;
134 case HidlWeaverReadStatus::INCORRECT_KEY:
135 _aidl_return->status = WeaverReadStatus::INCORRECT_KEY;
136 break;
137 case HidlWeaverReadStatus::THROTTLE:
138 _aidl_return->status = WeaverReadStatus::THROTTLE;
139 break;
140 default:
141 ADD_FAILURE() << "Unknown HIDL read status: " << static_cast<uint32_t>(status);
142 _aidl_return->status = WeaverReadStatus::FAILED;
143 break;
144 }
145 _aidl_return->value = value;
146 _aidl_return->timeout = timeout;
147 return ::ndk::ScopedAStatus::ok();
148 }
149
write(int32_t in_slotId,const std::vector<uint8_t> & in_key,const std::vector<uint8_t> & in_value)150 ::ndk::ScopedAStatus write(int32_t in_slotId, const std::vector<uint8_t>& in_key,
151 const std::vector<uint8_t>& in_value) {
152 auto status = hidl_weaver_->write(in_slotId, in_key, in_value);
153 switch (status) {
154 case HidlWeaverStatus::OK:
155 return ::ndk::ScopedAStatus::ok();
156 case HidlWeaverStatus::FAILED:
157 return ::ndk::ScopedAStatus::fromStatus(STATUS_FAILED_TRANSACTION);
158 default:
159 ADD_FAILURE() << "Unknown HIDL write status: " << status.description();
160 return ::ndk::ScopedAStatus::fromStatus(STATUS_FAILED_TRANSACTION);
161 }
162 }
163
164 private:
165 android::sp<HidlIWeaver> hidl_weaver_;
166 };
167
168 class WeaverTest : public ::testing::TestWithParam<std::tuple<std::string, std::string>> {
169 protected:
170 void SetUp() override;
TearDown()171 void TearDown() override {}
172 void FindFreeSlots();
173
174 std::unique_ptr<WeaverAdapter> weaver_;
175 WeaverConfig config_;
176 uint32_t first_free_slot_;
177 uint32_t last_free_slot_;
178 };
179
SetUp()180 void WeaverTest::SetUp() {
181 std::string api, instance_name;
182 std::tie(api, instance_name) = GetParam();
183 if (api == "hidl") {
184 weaver_.reset(new WeaverHidlAdapter(instance_name));
185 } else if (api == "aidl") {
186 weaver_.reset(new WeaverAidlAdapter(instance_name));
187 } else {
188 FAIL() << "Bad test parameterization";
189 }
190 ASSERT_TRUE(weaver_->isReady());
191
192 auto ret = weaver_->getConfig(&config_);
193 ASSERT_TRUE(ret.isOk());
194 ASSERT_GT(config_.slots, 0);
195 GTEST_LOG_(INFO) << "WeaverConfig: slots=" << config_.slots << ", keySize=" << config_.keySize
196 << ", valueSize=" << config_.valueSize;
197
198 FindFreeSlots();
199 GTEST_LOG_(INFO) << "First free slot is " << first_free_slot_ << ", last free slot is "
200 << last_free_slot_;
201 }
202
FindFreeSlots()203 void WeaverTest::FindFreeSlots() {
204 // Determine which Weaver slots are in use by the system. These slots can't be used by the test.
205 std::set<uint32_t> used_slots;
206 if (access(kSlotMapFile.c_str(), F_OK) == 0) {
207 std::string contents;
208 ASSERT_TRUE(android::base::ReadFileToString(kSlotMapFile, &contents))
209 << "Failed to read " << kSlotMapFile;
210 for (const auto& line : android::base::Split(contents, "\n")) {
211 auto trimmed_line = android::base::Trim(line);
212 if (trimmed_line[0] == '#' || trimmed_line[0] == '\0') continue;
213 auto slot_and_user = android::base::Split(trimmed_line, "=");
214 uint32_t slot;
215 ASSERT_TRUE(slot_and_user.size() == 2 &&
216 android::base::ParseUint(slot_and_user[0], &slot))
217 << "Error parsing " << kSlotMapFile << " at \"" << line << "\"";
218 GTEST_LOG_(INFO) << "Slot " << slot << " is in use by " << slot_and_user[1];
219 ASSERT_LT(slot, config_.slots);
220 used_slots.insert(slot);
221 }
222 }
223
224 // We should assert !used_slots.empty() here, but that can't be done yet due to
225 // config_disableWeaverOnUnsecuredUsers being supported. The value of that option is not
226 // accessible from here, so we have to assume it might be set to true.
227
228 // Find the first free slot.
229 int found = 0;
230 for (uint32_t i = 0; i < config_.slots; i++) {
231 if (used_slots.find(i) == used_slots.end()) {
232 first_free_slot_ = i;
233 found++;
234 break;
235 }
236 }
237 // Find the last free slot.
238 for (uint32_t i = config_.slots; i > 0; i--) {
239 if (used_slots.find(i - 1) == used_slots.end()) {
240 last_free_slot_ = i - 1;
241 found++;
242 break;
243 }
244 }
245 ASSERT_EQ(found, 2) << "All Weaver slots are already in use by the system";
246 }
247
248 /*
249 * Checks config values are suitably large
250 */
TEST_P(WeaverTest,GetConfig)251 TEST_P(WeaverTest, GetConfig) {
252 EXPECT_GE(config_.slots, 16u);
253 EXPECT_GE(config_.keySize, 16u);
254 EXPECT_GE(config_.valueSize, 16u);
255 }
256
257 /*
258 * Gets the config twice and checks they are the same
259 */
TEST_P(WeaverTest,GettingConfigMultipleTimesGivesSameResult)260 TEST_P(WeaverTest, GettingConfigMultipleTimesGivesSameResult) {
261 WeaverConfig config2;
262
263 auto ret = weaver_->getConfig(&config2);
264 ASSERT_TRUE(ret.isOk());
265
266 EXPECT_EQ(config_, config2);
267 }
268
269 /*
270 * Writes a key and value to the last free slot
271 */
TEST_P(WeaverTest,WriteToLastSlot)272 TEST_P(WeaverTest, WriteToLastSlot) {
273 const auto writeRet = weaver_->write(last_free_slot_, KEY, VALUE);
274 ASSERT_TRUE(writeRet.isOk());
275 }
276
277 /*
278 * Writes a key and value to a slot
279 * Reads the slot with the same key and receives the value that was previously written
280 */
TEST_P(WeaverTest,WriteFollowedByReadGivesTheSameValue)281 TEST_P(WeaverTest, WriteFollowedByReadGivesTheSameValue) {
282 const uint32_t slotId = first_free_slot_;
283 const auto ret = weaver_->write(slotId, KEY, VALUE);
284 ASSERT_TRUE(ret.isOk());
285
286 WeaverReadResponse response;
287 const auto readRet = weaver_->read(slotId, KEY, &response);
288 ASSERT_TRUE(readRet.isOk());
289 EXPECT_EQ(response.value, VALUE);
290 EXPECT_EQ(response.timeout, 0u);
291 EXPECT_EQ(response.status, WeaverReadStatus::OK);
292 }
293
294 /*
295 * Writes a key and value to a slot
296 * Overwrites the slot with a new key and value
297 * Reads the slot with the new key and receives the new value
298 */
TEST_P(WeaverTest,OverwritingSlotUpdatesTheValue)299 TEST_P(WeaverTest, OverwritingSlotUpdatesTheValue) {
300 const uint32_t slotId = first_free_slot_;
301 const auto initialWriteRet = weaver_->write(slotId, WRONG_KEY, VALUE);
302 ASSERT_TRUE(initialWriteRet.isOk());
303
304 const auto overwriteRet = weaver_->write(slotId, KEY, OTHER_VALUE);
305 ASSERT_TRUE(overwriteRet.isOk());
306
307 WeaverReadResponse response;
308 const auto readRet = weaver_->read(slotId, KEY, &response);
309 ASSERT_TRUE(readRet.isOk());
310 EXPECT_EQ(response.value, OTHER_VALUE);
311 EXPECT_EQ(response.timeout, 0u);
312 EXPECT_EQ(response.status, WeaverReadStatus::OK);
313 }
314
315 /*
316 * Writes a key and value to a slot
317 * Reads the slot with a different key so does not receive the value
318 */
TEST_P(WeaverTest,WriteFollowedByReadWithWrongKeyDoesNotGiveTheValue)319 TEST_P(WeaverTest, WriteFollowedByReadWithWrongKeyDoesNotGiveTheValue) {
320 const uint32_t slotId = first_free_slot_;
321 const auto writeRet = weaver_->write(slotId, KEY, VALUE);
322 ASSERT_TRUE(writeRet.isOk());
323
324 WeaverReadResponse response;
325 const auto readRet = weaver_->read(slotId, WRONG_KEY, &response);
326 ASSERT_TRUE(readRet.isOk());
327 EXPECT_TRUE(response.value.empty());
328 EXPECT_EQ(response.status, WeaverReadStatus::INCORRECT_KEY);
329 }
330
331 /*
332 * Writing to an invalid slot fails
333 */
TEST_P(WeaverTest,WritingToInvalidSlotFails)334 TEST_P(WeaverTest, WritingToInvalidSlotFails) {
335 if (config_.slots == std::numeric_limits<uint32_t>::max()) {
336 // If there are no invalid slots then pass
337 return;
338 }
339
340 const auto writeRet = weaver_->write(config_.slots, KEY, VALUE);
341 ASSERT_FALSE(writeRet.isOk());
342 }
343
344 /*
345 * Reading from an invalid slot fails rather than incorrect key
346 */
TEST_P(WeaverTest,ReadingFromInvalidSlotFails)347 TEST_P(WeaverTest, ReadingFromInvalidSlotFails) {
348 if (config_.slots == std::numeric_limits<uint32_t>::max()) {
349 // If there are no invalid slots then pass
350 return;
351 }
352
353 WeaverReadResponse response;
354 const auto readRet = weaver_->read(config_.slots, KEY, &response);
355 ASSERT_TRUE(readRet.isOk());
356 EXPECT_TRUE(response.value.empty());
357 EXPECT_EQ(response.timeout, 0u);
358 EXPECT_EQ(response.status, WeaverReadStatus::FAILED);
359 }
360
361 /*
362 * Writing a key that is too large fails
363 */
TEST_P(WeaverTest,WriteWithTooLargeKeyFails)364 TEST_P(WeaverTest, WriteWithTooLargeKeyFails) {
365 std::vector<uint8_t> bigKey(config_.keySize + 1);
366
367 const auto writeRet = weaver_->write(first_free_slot_, bigKey, VALUE);
368 ASSERT_FALSE(writeRet.isOk());
369 }
370
371 /*
372 * Writing a value that is too large fails
373 */
TEST_P(WeaverTest,WriteWithTooLargeValueFails)374 TEST_P(WeaverTest, WriteWithTooLargeValueFails) {
375 std::vector<uint8_t> bigValue(config_.valueSize + 1);
376
377 const auto writeRet = weaver_->write(first_free_slot_, KEY, bigValue);
378 ASSERT_FALSE(writeRet.isOk());
379 }
380
381 /*
382 * Reading with a key that is too large fails
383 */
TEST_P(WeaverTest,ReadWithTooLargeKeyFails)384 TEST_P(WeaverTest, ReadWithTooLargeKeyFails) {
385 std::vector<uint8_t> bigKey(config_.keySize + 1);
386
387 WeaverReadResponse response;
388 const auto readRet = weaver_->read(first_free_slot_, bigKey, &response);
389 ASSERT_TRUE(readRet.isOk());
390 EXPECT_TRUE(response.value.empty());
391 EXPECT_EQ(response.timeout, 0u);
392 EXPECT_EQ(response.status, WeaverReadStatus::FAILED);
393 }
394
395 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(WeaverTest);
396
397 // Instantiate the test for each HIDL Weaver service.
398 INSTANTIATE_TEST_SUITE_P(
399 PerHidlInstance, WeaverTest,
400 testing::Combine(testing::Values("hidl"),
401 testing::ValuesIn(android::hardware::getAllHalInstanceNames(
402 HidlIWeaver::descriptor))),
__anon62c0e71e0302(const testing::TestParamInfo<std::tuple<std::string, std::string>>& info) 403 [](const testing::TestParamInfo<std::tuple<std::string, std::string>>& info) {
404 return android::hardware::PrintInstanceNameToString(
405 testing::TestParamInfo<std::string>{std::get<1>(info.param), info.index});
406 });
407
408 // Instantiate the test for each AIDL Weaver service.
409 INSTANTIATE_TEST_SUITE_P(
410 PerAidlInstance, WeaverTest,
411 testing::Combine(testing::Values("aidl"),
412 testing::ValuesIn(android::getAidlHalInstanceNames(IWeaver::descriptor))),
__anon62c0e71e0402(const testing::TestParamInfo<std::tuple<std::string, std::string>>& info) 413 [](const testing::TestParamInfo<std::tuple<std::string, std::string>>& info) {
414 // This name_generator makes the instance name be included in the test case names, e.g.
415 // "PerAidlInstance/WeaverTest#GetConfig/0_android_hardware_weaver_IWeaver_default"
416 // instead of "PerAidlInstance/WeaverTest#GetConfig/0".
417 return android::PrintInstanceNameToString(
418 testing::TestParamInfo<std::string>{std::get<1>(info.param), info.index});
419 });
420
main(int argc,char ** argv)421 int main(int argc, char** argv) {
422 ::testing::InitGoogleTest(&argc, argv);
423 ABinderProcess_setThreadPoolMaxThreadCount(1);
424 ABinderProcess_startThreadPool();
425 return RUN_ALL_TESTS();
426 }
427