1 /*
2 * Copyright 2014 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 #pragma once
18
19 /*
20 * Utilities used to help with testing. Not used in production code.
21 */
22
23 #include <stdarg.h>
24
25 #include <algorithm>
26 #include <memory>
27 #include <ostream>
28 #include <string>
29 #include <vector>
30
31 #include <gtest/gtest.h>
32
33 #include <hardware/keymaster1.h>
34 #include <hardware/keymaster2.h>
35 #include <hardware/keymaster_defs.h>
36
37 #include <keymaster/android_keymaster_utils.h>
38 #include <keymaster/authorization_set.h>
39 #include <keymaster/keymaster_context.h>
40 #include <keymaster/km_version.h>
41 #include <keymaster/logger.h>
42
43 std::ostream& operator<<(std::ostream& os, const keymaster_key_param_t& param);
44 bool operator==(const keymaster_key_param_t& a, const keymaster_key_param_t& b);
45 std::string hex2str(std::string);
46
47 namespace keymaster {
48
49 bool operator==(const AuthorizationSet& a, const AuthorizationSet& b);
50 bool operator!=(const AuthorizationSet& a, const AuthorizationSet& b);
51
52 std::ostream& operator<<(std::ostream& os, const AuthorizationSet& set);
53
54 namespace test {
55
56 template <keymaster_tag_t Tag, typename KeymasterEnum>
contains(const AuthorizationSet & set,TypedEnumTag<KM_ENUM,Tag,KeymasterEnum> tag,KeymasterEnum val)57 bool contains(const AuthorizationSet& set, TypedEnumTag<KM_ENUM, Tag, KeymasterEnum> tag,
58 KeymasterEnum val) {
59 int pos = set.find(tag);
60 return pos != -1 && static_cast<KeymasterEnum>(set[pos].enumerated) == val;
61 }
62
63 template <keymaster_tag_t Tag, typename KeymasterEnum>
contains(const AuthorizationSet & set,TypedEnumTag<KM_ENUM_REP,Tag,KeymasterEnum> tag,KeymasterEnum val)64 bool contains(const AuthorizationSet& set, TypedEnumTag<KM_ENUM_REP, Tag, KeymasterEnum> tag,
65 KeymasterEnum val) {
66 int pos = -1;
67 while ((pos = set.find(tag, pos)) != -1)
68 if (static_cast<KeymasterEnum>(set[pos].enumerated) == val) return true;
69 return false;
70 }
71
72 template <keymaster_tag_t Tag>
contains(const AuthorizationSet & set,TypedTag<KM_UINT,Tag> tag,uint32_t val)73 bool contains(const AuthorizationSet& set, TypedTag<KM_UINT, Tag> tag, uint32_t val) {
74 int pos = set.find(tag);
75 return pos != -1 && set[pos].integer == val;
76 }
77
78 template <keymaster_tag_t Tag>
contains(const AuthorizationSet & set,TypedTag<KM_UINT_REP,Tag> tag,uint32_t val)79 bool contains(const AuthorizationSet& set, TypedTag<KM_UINT_REP, Tag> tag, uint32_t val) {
80 int pos = -1;
81 while ((pos = set.find(tag, pos)) != -1)
82 if (set[pos].integer == val) return true;
83 return false;
84 }
85
86 template <keymaster_tag_t Tag>
contains(const AuthorizationSet & set,TypedTag<KM_ULONG,Tag> tag,uint64_t val)87 bool contains(const AuthorizationSet& set, TypedTag<KM_ULONG, Tag> tag, uint64_t val) {
88 int pos = set.find(tag);
89 return pos != -1 && set[pos].long_integer == val;
90 }
91
92 template <keymaster_tag_t Tag>
contains(const AuthorizationSet & set,TypedTag<KM_BYTES,Tag> tag,const std::string & val)93 bool contains(const AuthorizationSet& set, TypedTag<KM_BYTES, Tag> tag, const std::string& val) {
94 int pos = set.find(tag);
95 return pos != -1 && std::string(reinterpret_cast<const char*>(set[pos].blob.data),
96 set[pos].blob.data_length) == val;
97 }
98
99 template <keymaster_tag_t Tag>
contains(const AuthorizationSet & set,TypedTag<KM_BIGNUM,Tag> tag,const std::string & val)100 bool contains(const AuthorizationSet& set, TypedTag<KM_BIGNUM, Tag> tag, const std::string& val) {
101 int pos = set.find(tag);
102 return pos != -1 && std::string(reinterpret_cast<const char*>(set[pos].blob.data),
103 set[pos].blob.data_length) == val;
104 }
105
contains(const AuthorizationSet & set,keymaster_tag_t tag)106 inline bool contains(const AuthorizationSet& set, keymaster_tag_t tag) {
107 return set.find(tag) != -1;
108 }
109
110 class StdoutLogger : public Logger {
111 public:
StdoutLogger()112 StdoutLogger() { set_instance(this); }
113
log_msg(LogLevel level,const char * fmt,va_list args)114 int log_msg(LogLevel level, const char* fmt, va_list args) const {
115 int output_len = 0;
116 switch (level) {
117 case DEBUG_LVL:
118 output_len = printf("DEBUG: ");
119 break;
120 case INFO_LVL:
121 output_len = printf("INFO: ");
122 break;
123 case WARNING_LVL:
124 output_len = printf("WARNING: ");
125 break;
126 case ERROR_LVL:
127 output_len = printf("ERROR: ");
128 break;
129 case SEVERE_LVL:
130 output_len = printf("SEVERE: ");
131 break;
132 }
133
134 output_len += vprintf(fmt, args);
135 output_len += printf("\n");
136 return output_len;
137 }
138 };
139
make_string(const uint8_t * data,size_t length)140 inline std::string make_string(const uint8_t* data, size_t length) {
141 return std::string(reinterpret_cast<const char*>(data), length);
142 }
143
make_string(const uint8_t (& a)[N])144 template <size_t N> std::string make_string(const uint8_t (&a)[N]) {
145 return make_string(a, N);
146 }
147
148 /**
149 * Keymaster2TestInstance is used to parameterize Keymaster2Tests. Its main function is to create a
150 * keymaster2_device_t to which test calls can be directed. It also provides a place to specify
151 * various bits of alternative behavior, in cases where different devices are expected to behave
152 * differently (any such cases are a potential bug, but sometimes they may make sense).
153 */
154 class Keymaster2TestInstanceCreator {
155 public:
~Keymaster2TestInstanceCreator()156 virtual ~Keymaster2TestInstanceCreator(){};
157 virtual keymaster2_device_t* CreateDevice() const = 0;
158
minimal_digest_set()159 virtual int minimal_digest_set() const { return false; }
160 virtual bool is_keymaster1_hw() const = 0;
is_keymint()161 virtual bool is_keymint() const { return false; }
162 virtual KeymasterContext* keymaster_context() const = 0;
163 virtual KmVersion km_version() const = 0;
164
165 virtual std::string name() const = 0;
166 };
167
168 // Use a shared_ptr because it's copyable.
169 typedef std::shared_ptr<Keymaster2TestInstanceCreator> InstanceCreatorPtr;
170
171 std::ostream& operator<<(std::ostream& os, const InstanceCreatorPtr& instance_creator);
172
173 const uint64_t OP_HANDLE_SENTINEL = 0xFFFFFFFFFFFFFFFF;
174 class Keymaster2Test : public testing::TestWithParam<InstanceCreatorPtr> {
175 protected:
176 Keymaster2Test();
177 ~Keymaster2Test();
178
179 keymaster2_device_t* device();
180
181 keymaster_error_t GenerateKey(const AuthorizationSetBuilder& builder);
182
183 keymaster_error_t DeleteKey();
184
185 keymaster_error_t ImportKey(const AuthorizationSetBuilder& builder,
186 keymaster_key_format_t format, const std::string& key_material);
187
188 keymaster_error_t ExportKey(keymaster_key_format_t format, std::string* export_data);
189
190 keymaster_error_t GetCharacteristics();
191
192 keymaster_error_t BeginOperation(keymaster_purpose_t purpose);
193 keymaster_error_t BeginOperation(keymaster_purpose_t purpose, const AuthorizationSet& input_set,
194 AuthorizationSet* output_set = nullptr);
195
196 keymaster_error_t UpdateOperation(const std::string& message, std::string* output,
197 size_t* input_consumed);
198 keymaster_error_t UpdateOperation(const AuthorizationSet& additional_params,
199 const std::string& message, AuthorizationSet* output_params,
200 std::string* output, size_t* input_consumed);
201
202 keymaster_error_t FinishOperation(std::string* output);
203 keymaster_error_t FinishOperation(const std::string& input, const std::string& signature,
204 std::string* output);
FinishOperation(const AuthorizationSet & additional_params,const std::string & input,const std::string & signature,std::string * output)205 keymaster_error_t FinishOperation(const AuthorizationSet& additional_params,
206 const std::string& input, const std::string& signature,
207 std::string* output) {
208 return FinishOperation(additional_params, input, signature, nullptr /* output_params */,
209 output);
210 }
211 keymaster_error_t FinishOperation(const AuthorizationSet& additional_params,
212 const std::string& input, const std::string& signature,
213 AuthorizationSet* output_params, std::string* output);
214
215 keymaster_error_t AbortOperation();
216
217 keymaster_error_t AttestKey(const std::string& attest_challenge,
218 const std::string& attest_app_id, keymaster_cert_chain_t* chain);
219
220 keymaster_error_t UpgradeKey(const AuthorizationSet& upgrade_params);
221
222 keymaster_error_t GetVersion(uint8_t* major, uint8_t* minor, uint8_t* subminor);
223 std::string ProcessMessage(keymaster_purpose_t purpose, const std::string& message);
224 std::string ProcessMessage(keymaster_purpose_t purpose, const std::string& message,
225 const AuthorizationSet& begin_params,
226 const AuthorizationSet& update_params,
227 AuthorizationSet* output_params = nullptr);
228 std::string ProcessMessage(keymaster_purpose_t purpose, const std::string& message,
229 const std::string& signature, const AuthorizationSet& begin_params,
230 const AuthorizationSet& update_params,
231 AuthorizationSet* output_params = nullptr);
232 std::string ProcessMessage(keymaster_purpose_t purpose, const std::string& message,
233 const std::string& signature);
234
235 void SignMessage(const std::string& message, std::string* signature, keymaster_digest_t digest);
236 void SignMessage(const std::string& message, std::string* signature, keymaster_digest_t digest,
237 keymaster_padding_t padding);
238 void MacMessage(const std::string& message, std::string* signature, size_t mac_length);
239
240 void VerifyMessage(const std::string& message, const std::string& signature,
241 keymaster_digest_t digest);
242 void VerifyMessage(const std::string& message, const std::string& signature,
243 keymaster_digest_t digest, keymaster_padding_t padding);
244 void VerifyMac(const std::string& message, const std::string& signature);
245
246 std::string EncryptMessage(const std::string& message, keymaster_padding_t padding,
247 std::string* generated_nonce = nullptr);
248 std::string EncryptMessage(const std::string& message, keymaster_digest_t digest,
249 keymaster_digest_t mgf_digest, keymaster_padding_t padding,
250 std::string* generated_nonce = nullptr);
251 std::string EncryptMessage(const std::string& message, keymaster_digest_t digest,
252 keymaster_padding_t padding, std::string* generated_nonce = nullptr);
253 std::string EncryptMessage(const std::string& message, keymaster_block_mode_t block_mode,
254 keymaster_padding_t padding, std::string* generated_nonce = nullptr);
255 std::string EncryptMessage(const AuthorizationSet& update_params, const std::string& message,
256 keymaster_digest_t digest, keymaster_digest_t mgf_digest,
257 keymaster_padding_t padding, std::string* generated_nonce = nullptr);
258 std::string EncryptMessage(const AuthorizationSet& update_params, const std::string& message,
259 keymaster_digest_t digest, keymaster_padding_t padding,
260 std::string* generated_nonce = nullptr);
261 std::string EncryptMessage(const AuthorizationSet& update_params, const std::string& message,
262 keymaster_block_mode_t block_mode, keymaster_padding_t padding,
263 std::string* generated_nonce = nullptr);
264 std::string EncryptMessageWithParams(const std::string& message,
265 const AuthorizationSet& begin_params,
266 const AuthorizationSet& update_params,
267 AuthorizationSet* output_params);
268
269 std::string DecryptMessage(const std::string& ciphertext, keymaster_padding_t padding);
270 std::string DecryptMessage(const std::string& ciphertext, keymaster_digest_t digest,
271 keymaster_padding_t padding);
272 std::string DecryptMessage(const std::string& ciphertext, keymaster_block_mode_t block_mode,
273 keymaster_padding_t padding);
274 std::string DecryptMessage(const std::string& ciphertext, keymaster_digest_t digest,
275 keymaster_padding_t padding, const std::string& nonce);
276 std::string DecryptMessage(const std::string& ciphertext, keymaster_digest_t digest,
277 keymaster_digest_t mgf_digest, keymaster_padding_t padding);
278 std::string DecryptMessage(const std::string& ciphertext, keymaster_block_mode_t block_mode,
279 keymaster_padding_t padding, const std::string& nonce);
280 std::string DecryptMessage(const AuthorizationSet& update_params, const std::string& ciphertext,
281 keymaster_digest_t digest, keymaster_padding_t padding,
282 const std::string& nonce);
283 std::string DecryptMessage(const AuthorizationSet& update_params, const std::string& ciphertext,
284 keymaster_block_mode_t block_mode, keymaster_padding_t padding,
285 const std::string& nonce);
286 std::string DecryptMessageWithParams(const std::string& message,
287 const AuthorizationSet& begin_params,
288 const AuthorizationSet& update_params,
289 AuthorizationSet* output_params);
290
291 void CheckHmacTestVector(const std::string& key, const std::string& message,
292 keymaster_digest_t digest, std::string expected_mac);
293 void CheckAesOcbTestVector(const std::string& key, const std::string& nonce,
294 const std::string& associated_data, const std::string& message,
295 const std::string& expected_ciphertext);
296 void CheckAesCtrTestVector(const std::string& key, const std::string& nonce,
297 const std::string& message, const std::string& expected_ciphertext);
298 void CheckTripleDesTestVector(keymaster_purpose_t purpose, keymaster_block_mode_t mode,
299 keymaster_padding_t padding, const std::string& key,
300 const std::string& iv, const std::string& message,
301 const std::string& expected_ciphertext);
302 AuthorizationSet UserAuthParams();
303 AuthorizationSet ClientParams();
304
305 template <typename T>
ResponseContains(const std::vector<T> & expected,const T * values,size_t len)306 bool ResponseContains(const std::vector<T>& expected, const T* values, size_t len) {
307 return expected.size() == len &&
308 std::is_permutation(values, values + len, expected.begin());
309 }
310
ResponseContains(T expected,const T * values,size_t len)311 template <typename T> bool ResponseContains(T expected, const T* values, size_t len) {
312 return (len == 1 && *values == expected);
313 }
314
315 AuthorizationSet hw_enforced();
316 AuthorizationSet sw_enforced();
317
318 void FreeCharacteristics();
319 void FreeKeyBlob();
320
321 void corrupt_key_blob();
322
set_key_blob(const uint8_t * key,size_t key_length)323 void set_key_blob(const uint8_t* key, size_t key_length) {
324 FreeKeyBlob();
325 blob_.key_material = key;
326 blob_.key_material_size = key_length;
327 }
328
set_key_blob(KeymasterKeyBlob blob)329 void set_key_blob(KeymasterKeyBlob blob) { blob_ = blob.release(); }
set_key_characteristics(const AuthorizationSet & hw_enforced,const AuthorizationSet & sw_enforced)330 void set_key_characteristics(const AuthorizationSet& hw_enforced,
331 const AuthorizationSet& sw_enforced) {
332 FreeCharacteristics();
333 hw_enforced.CopyToParamSet(&characteristics_.hw_enforced);
334 sw_enforced.CopyToParamSet(&characteristics_.sw_enforced);
335 }
336
client_params()337 AuthorizationSet client_params() {
338 return AuthorizationSet(client_params_, sizeof(client_params_) / sizeof(client_params_[0]));
339 }
340
341 private:
342 keymaster2_device_t* device_;
343 keymaster_blob_t client_id_ = {.data = reinterpret_cast<const uint8_t*>("app_id"),
344 .data_length = 6};
345 keymaster_key_param_t client_params_[1] = {
346 Authorization(TAG_APPLICATION_ID, client_id_.data, client_id_.data_length)};
347
348 uint64_t op_handle_;
349
350 keymaster_key_blob_t blob_;
351 keymaster_key_characteristics_t characteristics_;
352 };
353
354 /**
355 * This function takes a keymaster1_device_t and wraps it in an adapter that supports only
356 * KM_DIGEST_SHA_2_256.
357 */
358 keymaster1_device_t* make_device_sha256_only(keymaster1_device_t* device);
359
360 } // namespace test
361 } // namespace keymaster
362