1 /*
2  * Copyright (C) 2017 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 #include "KeymasterHidlTest.h"
18 
19 namespace android {
20 namespace hardware {
21 namespace keymaster {
22 namespace V4_0 {
23 namespace test {
24 
25 /**
26  * HmacKeySharingTest extends KeymasterHidlTest with some utilities that make writing HMAC sharing
27  * tests easier.
28  */
29 class HmacKeySharingTest : public KeymasterHidlTest {
30    protected:
allKeymasters()31      const std::vector<sp<IKeymasterDevice>>& allKeymasters() {
32          if (all_keymasters_.empty()) {
33              auto names = android::hardware::getAllHalInstanceNames(IKeymasterDevice::descriptor);
34              for (const auto& name : names) {
35                  all_keymasters_.push_back(IKeymasterDevice::getService(name));
36              }
37          }
38          return all_keymasters_;
39      }
40 
41     struct GetParamsResult {
42         ErrorCode error;
43         HmacSharingParameters params;
tieandroid::hardware::keymaster::V4_0::test::HmacKeySharingTest::GetParamsResult44         auto tie() { return std::tie(error, params); }
45     };
46 
47     struct ComputeHmacResult {
48         ErrorCode error;
49         HidlBuf sharing_check;
tieandroid::hardware::keymaster::V4_0::test::HmacKeySharingTest::ComputeHmacResult50         auto tie() { return std::tie(error, sharing_check); }
51     };
52 
53     using KeymasterVec = std::vector<sp<IKeymasterDevice>>;
54     using ByteString = std::basic_string<uint8_t>;
55     // using NonceVec = std::vector<HidlBuf>;
56 
getHmacSharingParameters(IKeymasterDevice & keymaster)57     GetParamsResult getHmacSharingParameters(IKeymasterDevice& keymaster) {
58         GetParamsResult result;
59         EXPECT_TRUE(keymaster
60                         .getHmacSharingParameters([&](auto error, auto params) {
61                             result.tie() = std::tie(error, params);
62                         })
63                         .isOk());
64         return result;
65     }
66 
getHmacSharingParameters(const KeymasterVec & keymasters)67     hidl_vec<HmacSharingParameters> getHmacSharingParameters(const KeymasterVec& keymasters) {
68         std::vector<HmacSharingParameters> paramsVec;
69         for (auto& keymaster : keymasters) {
70             auto result = getHmacSharingParameters(*keymaster);
71             EXPECT_EQ(ErrorCode::OK, result.error);
72             if (result.error == ErrorCode::OK) paramsVec.push_back(std::move(result.params));
73         }
74         return paramsVec;
75     }
76 
computeSharedHmac(IKeymasterDevice & keymaster,const hidl_vec<HmacSharingParameters> & params)77     ComputeHmacResult computeSharedHmac(IKeymasterDevice& keymaster,
78                                         const hidl_vec<HmacSharingParameters>& params) {
79         ComputeHmacResult result;
80         EXPECT_TRUE(keymaster
81                         .computeSharedHmac(params,
82                                            [&](auto error, auto params) {
83                                                result.tie() = std::tie(error, params);
84                                            })
85                         .isOk());
86         return result;
87     }
88 
computeSharedHmac(const KeymasterVec & keymasters,const hidl_vec<HmacSharingParameters> & paramsVec)89     std::vector<ComputeHmacResult> computeSharedHmac(
90         const KeymasterVec& keymasters, const hidl_vec<HmacSharingParameters>& paramsVec) {
91         std::vector<ComputeHmacResult> resultVec;
92         for (auto& keymaster : keymasters) {
93             resultVec.push_back(computeSharedHmac(*keymaster, paramsVec));
94         }
95         return resultVec;
96     }
97 
copyNonces(const hidl_vec<HmacSharingParameters> & paramsVec)98     std::vector<ByteString> copyNonces(const hidl_vec<HmacSharingParameters>& paramsVec) {
99         std::vector<ByteString> nonces;
100         for (auto& param : paramsVec) {
101             nonces.emplace_back(param.nonce.data(), param.nonce.size());
102         }
103         return nonces;
104     }
105 
verifyResponses(const HidlBuf & expected,const std::vector<ComputeHmacResult> & responses)106     void verifyResponses(const HidlBuf& expected, const std::vector<ComputeHmacResult>& responses) {
107         for (auto& response : responses) {
108             EXPECT_EQ(ErrorCode::OK, response.error);
109             EXPECT_EQ(expected, response.sharing_check) << "Sharing check values should match.";
110         }
111     }
112 
113   private:
114     static std::vector<sp<IKeymasterDevice>> all_keymasters_;
115 };
116 
117 std::vector<sp<IKeymasterDevice>> HmacKeySharingTest::all_keymasters_;
118 
TEST_P(HmacKeySharingTest,GetParameters)119 TEST_P(HmacKeySharingTest, GetParameters) {
120     auto result1 = getHmacSharingParameters(keymaster());
121     EXPECT_EQ(ErrorCode::OK, result1.error);
122 
123     auto result2 = getHmacSharingParameters(keymaster());
124     EXPECT_EQ(ErrorCode::OK, result2.error);
125 
126     ASSERT_EQ(result1.params.seed, result2.params.seed)
127         << "A given keymaster should always return the same seed.";
128     ASSERT_EQ(result1.params.nonce, result2.params.nonce)
129         << "A given keymaster should always return the same nonce until restart.";
130 }
131 
TEST_P(HmacKeySharingTest,ComputeSharedHmac)132 TEST_P(HmacKeySharingTest, ComputeSharedHmac) {
133     auto params = getHmacSharingParameters(allKeymasters());
134     ASSERT_EQ(allKeymasters().size(), params.size())
135             << "One or more keymasters failed to provide parameters.";
136 
137     auto nonces = copyNonces(params);
138     EXPECT_EQ(allKeymasters().size(), nonces.size());
139     std::sort(nonces.begin(), nonces.end());
140     std::unique(nonces.begin(), nonces.end());
141     EXPECT_EQ(allKeymasters().size(), nonces.size());
142 
143     auto responses = computeSharedHmac(allKeymasters(), params);
144     ASSERT_GT(responses.size(), 0U);
145     verifyResponses(responses[0].sharing_check, responses);
146 
147     // Do it a second time.  Should get the same answers.
148     params = getHmacSharingParameters(allKeymasters());
149     ASSERT_EQ(allKeymasters().size(), params.size())
150             << "One or more keymasters failed to provide parameters.";
151 
152     responses = computeSharedHmac(allKeymasters(), params);
153     ASSERT_GT(responses.size(), 0U);
154     ASSERT_EQ(32U, responses[0].sharing_check.size());
155     verifyResponses(responses[0].sharing_check, responses);
156 }
157 
158 template <class F>
159 class final_action {
160    public:
final_action(F f)161      explicit final_action(F f) : f_(std::move(f)) {}
~final_action()162      ~final_action() { f_(); }
163 
164    private:
165     F f_;
166 };
167 
168 template <class F>
finally(const F & f)169 inline final_action<F> finally(const F& f) {
170     return final_action<F>(f);
171 }
172 
TEST_P(HmacKeySharingTest,ComputeSharedHmacCorruptNonce)173 TEST_P(HmacKeySharingTest, ComputeSharedHmacCorruptNonce) {
174     // Important: The execution of this test gets the keymaster implementations on the device out of
175     // sync with respect to the HMAC key.  Granted that VTS tests aren't run on in-use production
176     // devices, this still has the potential to cause confusion.  To mitigate that, we always
177     // (barring crashes :-/) re-run the unmodified agreement process on our way out.
178     auto fixup_hmac = finally([&]() {
179         computeSharedHmac(allKeymasters(), getHmacSharingParameters(allKeymasters()));
180     });
181 
182     auto params = getHmacSharingParameters(allKeymasters());
183     ASSERT_EQ(allKeymasters().size(), params.size())
184             << "One or more keymasters failed to provide parameters.";
185 
186     // All should be well in the normal case
187     auto responses = computeSharedHmac(allKeymasters(), params);
188 
189     ASSERT_GT(responses.size(), 0U);
190     HidlBuf correct_response = responses[0].sharing_check;
191     verifyResponses(correct_response, responses);
192 
193     // Pick a random param, a random byte within the param's nonce, and a random bit within
194     // the byte.  Flip that bit.
195     size_t param_to_tweak = rand() % params.size();
196     uint8_t byte_to_tweak = rand() % sizeof(params[param_to_tweak].nonce);
197     uint8_t bit_to_tweak = rand() % 8;
198     params[param_to_tweak].nonce[byte_to_tweak] ^= (1 << bit_to_tweak);
199 
200     responses = computeSharedHmac(allKeymasters(), params);
201     for (size_t i = 0; i < responses.size(); ++i) {
202         if (i == param_to_tweak) {
203             EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, responses[i].error)
204                 << "Keymaster that provided tweaked param should fail to compute HMAC key";
205         } else {
206             EXPECT_EQ(ErrorCode::OK, responses[i].error) << "Others should succeed";
207             EXPECT_NE(correct_response, responses[i].sharing_check)
208                 << "Others should calculate a different HMAC key, due to the tweaked nonce.";
209         }
210     }
211 }
212 
TEST_P(HmacKeySharingTest,ComputeSharedHmacCorruptSeed)213 TEST_P(HmacKeySharingTest, ComputeSharedHmacCorruptSeed) {
214     // Important: The execution of this test gets the keymaster implementations on the device out of
215     // sync with respect to the HMAC key.  Granted that VTS tests aren't run on in-use production
216     // devices, this still has the potential to cause confusion.  To mitigate that, we always
217     // (barring crashes :-/) re-run the unmodified agreement process on our way out.
218     auto fixup_hmac = finally([&]() {
219         computeSharedHmac(allKeymasters(), getHmacSharingParameters(allKeymasters()));
220     });
221 
222     auto params = getHmacSharingParameters(allKeymasters());
223     ASSERT_EQ(allKeymasters().size(), params.size())
224             << "One or more keymasters failed to provide parameters.";
225 
226     // All should be well in the normal case
227     auto responses = computeSharedHmac(allKeymasters(), params);
228 
229     ASSERT_GT(responses.size(), 0U);
230     HidlBuf correct_response = responses[0].sharing_check;
231     verifyResponses(correct_response, responses);
232 
233     // Pick a random param and modify the seed.  We just increase the seed length by 1.  It doesn't
234     // matter what value is in the additional byte; it changes the seed regardless.
235     auto param_to_tweak = rand() % params.size();
236     auto& to_tweak = params[param_to_tweak].seed;
237     ASSERT_TRUE(to_tweak.size() == 32 || to_tweak.size() == 0);
238     if (!to_tweak.size()) {
239         to_tweak.resize(32);  // Contents don't matter; a little randomization is nice.
240     }
241     to_tweak[0]++;
242 
243     responses = computeSharedHmac(allKeymasters(), params);
244     for (size_t i = 0; i < responses.size(); ++i) {
245         if (i == param_to_tweak) {
246             EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, responses[i].error)
247                 << "Keymaster that provided tweaked param should fail to compute HMAC key ";
248         } else {
249             EXPECT_EQ(ErrorCode::OK, responses[i].error) << "Others should succeed";
250             EXPECT_NE(correct_response, responses[i].sharing_check)
251                 << "Others should calculate a different HMAC key, due to the tweaked nonce.";
252         }
253     }
254 }
255 
256 INSTANTIATE_KEYMASTER_HIDL_TEST(HmacKeySharingTest);
257 
258 }  // namespace test
259 }  // namespace V4_0
260 }  // namespace keymaster
261 }  // namespace hardware
262 }  // namespace android
263