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#include "android_keymaster_test_utils.h"
18
19#include <algorithm>
20
21#include <openssl/rand.h>
22
23#include <keymaster/android_keymaster_messages.h>
24#include <keymaster/android_keymaster_utils.h>
25
26using std::copy_if;
27using std::find_if;
28using std::is_permutation;
29using std::ostream;
30using std::string;
31using std::vector;
32
33std::ostream& operator<<(std::ostream& os, const keymaster_key_param_t& param) {
34    os << "Tag: " << keymaster_tag_mask_type(param.tag);
35    switch (keymaster_tag_get_type(param.tag)) {
36    case KM_INVALID:
37        os << " Invalid";
38        break;
39    case KM_UINT_REP:
40        os << " (Rep)";
41    /* Falls through */
42    case KM_UINT:
43        os << " Int: " << param.integer;
44        break;
45    case KM_ENUM_REP:
46        os << " (Rep)";
47    /* Falls through */
48    case KM_ENUM:
49        os << " Enum: " << param.enumerated;
50        break;
51    case KM_ULONG_REP:
52        os << " (Rep)";
53    /* Falls through */
54    case KM_ULONG:
55        os << " Long: " << param.long_integer;
56        break;
57    case KM_DATE:
58        os << " Date: " << param.date_time;
59        break;
60    case KM_BOOL:
61        os << " Bool: " << param.boolean;
62        break;
63    case KM_BIGNUM:
64        os << " Bignum: ";
65        break;
66    case KM_BYTES:
67        os << " Bytes: ";
68        break;
69    }
70    return os;
71}
72
73bool operator==(const keymaster_key_param_t& a, const keymaster_key_param_t& b) {
74    if (a.tag != b.tag) {
75        return false;
76    }
77
78    switch (keymaster_tag_get_type(a.tag)) {
79    case KM_INVALID:
80        return true;
81    case KM_UINT_REP:
82    case KM_UINT:
83        return a.integer == b.integer;
84    case KM_ENUM_REP:
85    case KM_ENUM:
86        return a.enumerated == b.enumerated;
87    case KM_ULONG:
88    case KM_ULONG_REP:
89        return a.long_integer == b.long_integer;
90    case KM_DATE:
91        return a.date_time == b.date_time;
92    case KM_BOOL:
93        return a.boolean == b.boolean;
94    case KM_BIGNUM:
95    case KM_BYTES:
96        if ((a.blob.data == NULL || b.blob.data == NULL) && a.blob.data != b.blob.data)
97            return false;
98        return a.blob.data_length == b.blob.data_length &&
99               (memcmp(a.blob.data, b.blob.data, a.blob.data_length) == 0);
100    }
101
102    return false;
103}
104
105static char hex_value[256] = {
106    0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0,  0,  0,  0,  0,  0,
107    0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0,  0,  0,  0,  0,  0,
108    0, 1,  2,  3,  4,  5,  6,  7, 8, 9, 0, 0, 0, 0, 0, 0,  // '0'..'9'
109    0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0,  // 'A'..'F'
110    0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 11, 12, 13, 14, 15, 0,
111    0, 0,  0,  0,  0,  0,  0,  0,  // 'a'..'f'
112    0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0,  0,  0,  0,  0,  0,
113    0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0,  0,  0,  0,  0,  0,
114    0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0,  0,  0,  0,  0,  0,
115    0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0,  0,  0,  0,  0,  0,
116    0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0,  0,  0,  0,  0,  0,
117    0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0,  0,  0,  0,  0,  0};
118
119string hex2str(string a) {
120    string b;
121    size_t num = a.size() / 2;
122    b.resize(num);
123    for (size_t i = 0; i < num; i++) {
124        b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
125    }
126    return b;
127}
128
129namespace keymaster {
130
131bool operator==(const AuthorizationSet& a, const AuthorizationSet& b) {
132    if (a.size() != b.size())
133        return false;
134
135    for (size_t i = 0; i < a.size(); ++i)
136        if (!(a[i] == b[i]))
137            return false;
138    return true;
139}
140
141bool operator!=(const AuthorizationSet& a, const AuthorizationSet& b) {
142    return !(a == b);
143}
144
145std::ostream& operator<<(std::ostream& os, const AuthorizationSet& set) {
146    if (set.size() == 0)
147        os << "(Empty)" << std::endl;
148    for (size_t i = 0; i < set.size(); ++i) {
149        os << set[i] << std::endl;
150    }
151    return os;
152}
153
154namespace test {
155
156Keymaster1Test::Keymaster1Test() : op_handle_(OP_HANDLE_SENTINEL), characteristics_(NULL) {
157    blob_.key_material = NULL;
158    RAND_seed("foobar", 6);
159    blob_.key_material = 0;
160    device_ = GetParam()->CreateDevice();
161}
162
163Keymaster1Test::~Keymaster1Test() {
164    FreeCharacteristics();
165    FreeKeyBlob();
166    device_->common.close(reinterpret_cast<hw_device_t*>(device_));
167}
168
169keymaster1_device_t* Keymaster1Test::device() {
170    return device_;
171}
172
173keymaster_error_t Keymaster1Test::GenerateKey(const AuthorizationSetBuilder& builder) {
174    AuthorizationSet params(builder.build());
175    params.push_back(UserAuthParams());
176    params.push_back(ClientParams());
177
178    FreeKeyBlob();
179    FreeCharacteristics();
180    return device()->generate_key(device(), &params, &blob_, &characteristics_);
181}
182
183keymaster_error_t Keymaster1Test::ImportKey(const AuthorizationSetBuilder& builder,
184                                            keymaster_key_format_t format,
185                                            const string& key_material) {
186    AuthorizationSet params(builder.build());
187    params.push_back(UserAuthParams());
188    params.push_back(ClientParams());
189
190    FreeKeyBlob();
191    FreeCharacteristics();
192    keymaster_blob_t key = {reinterpret_cast<const uint8_t*>(key_material.c_str()),
193                            key_material.length()};
194    return device()->import_key(device(), &params, format, &key, &blob_, &characteristics_);
195}
196
197AuthorizationSet Keymaster1Test::UserAuthParams() {
198    AuthorizationSet set;
199    set.push_back(TAG_USER_ID, 7);
200    set.push_back(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD);
201    set.push_back(TAG_AUTH_TIMEOUT, 300);
202    return set;
203}
204
205AuthorizationSet Keymaster1Test::ClientParams() {
206    AuthorizationSet set;
207    set.push_back(TAG_APPLICATION_ID, "app_id", 6);
208    return set;
209}
210
211keymaster_error_t Keymaster1Test::BeginOperation(keymaster_purpose_t purpose) {
212    AuthorizationSet in_params(client_params());
213    keymaster_key_param_set_t out_params;
214    keymaster_error_t error =
215        device()->begin(device(), purpose, &blob_, &in_params, &out_params, &op_handle_);
216    EXPECT_EQ(0U, out_params.length);
217    EXPECT_TRUE(out_params.params == nullptr);
218    return error;
219}
220
221keymaster_error_t Keymaster1Test::BeginOperation(keymaster_purpose_t purpose,
222                                                 const AuthorizationSet& input_set,
223                                                 AuthorizationSet* output_set) {
224    keymaster_key_param_set_t out_params;
225    keymaster_error_t error =
226        device()->begin(device(), purpose, &blob_, &input_set, &out_params, &op_handle_);
227    if (error == KM_ERROR_OK) {
228        if (output_set) {
229            output_set->Reinitialize(out_params);
230        } else {
231            EXPECT_EQ(0U, out_params.length);
232            EXPECT_TRUE(out_params.params == nullptr);
233        }
234        keymaster_free_param_set(&out_params);
235    }
236    return error;
237}
238
239keymaster_error_t Keymaster1Test::UpdateOperation(const string& message, string* output,
240                                                  size_t* input_consumed) {
241    EXPECT_NE(op_handle_, OP_HANDLE_SENTINEL);
242    keymaster_blob_t input = {reinterpret_cast<const uint8_t*>(message.c_str()), message.length()};
243    keymaster_blob_t out_tmp;
244    keymaster_key_param_set_t out_params;
245    keymaster_error_t error = device()->update(device(), op_handle_, nullptr /* params */, &input,
246                                               input_consumed, &out_params, &out_tmp);
247    if (error == KM_ERROR_OK && out_tmp.data)
248        output->append(reinterpret_cast<const char*>(out_tmp.data), out_tmp.data_length);
249    free(const_cast<uint8_t*>(out_tmp.data));
250    return error;
251}
252
253keymaster_error_t Keymaster1Test::UpdateOperation(const AuthorizationSet& additional_params,
254                                                  const string& message,
255                                                  AuthorizationSet* output_params, string* output,
256                                                  size_t* input_consumed) {
257    EXPECT_NE(op_handle_, OP_HANDLE_SENTINEL);
258    keymaster_blob_t input = {reinterpret_cast<const uint8_t*>(message.c_str()), message.length()};
259    keymaster_blob_t out_tmp;
260    keymaster_key_param_set_t out_params;
261    keymaster_error_t error = device()->update(device(), op_handle_, &additional_params, &input,
262                                               input_consumed, &out_params, &out_tmp);
263    if (error == KM_ERROR_OK && out_tmp.data)
264        output->append(reinterpret_cast<const char*>(out_tmp.data), out_tmp.data_length);
265    free((void*)out_tmp.data);
266    if (output_params)
267        output_params->Reinitialize(out_params);
268    keymaster_free_param_set(&out_params);
269    return error;
270}
271
272keymaster_error_t Keymaster1Test::FinishOperation(string* output) {
273    return FinishOperation("", output);
274}
275
276keymaster_error_t Keymaster1Test::FinishOperation(const string& signature, string* output) {
277    AuthorizationSet additional_params;
278    AuthorizationSet output_params;
279    return FinishOperation(additional_params, signature, &output_params, output);
280}
281
282keymaster_error_t Keymaster1Test::FinishOperation(const AuthorizationSet& additional_params,
283                                                  const string& signature,
284                                                  AuthorizationSet* output_params, string* output) {
285    keymaster_blob_t sig = {reinterpret_cast<const uint8_t*>(signature.c_str()),
286                            signature.length()};
287    keymaster_blob_t out_tmp;
288    keymaster_key_param_set_t out_params;
289    keymaster_error_t error =
290        device()->finish(device(), op_handle_, &additional_params, &sig, &out_params, &out_tmp);
291    if (error != KM_ERROR_OK) {
292        EXPECT_TRUE(out_tmp.data == nullptr);
293        EXPECT_TRUE(out_params.params == nullptr);
294        return error;
295    }
296
297    if (out_tmp.data)
298        output->append(reinterpret_cast<const char*>(out_tmp.data), out_tmp.data_length);
299    free((void*)out_tmp.data);
300    if (output_params)
301        output_params->Reinitialize(out_params);
302    keymaster_free_param_set(&out_params);
303    return error;
304}
305
306keymaster_error_t Keymaster1Test::AbortOperation() {
307    return device()->abort(device(), op_handle_);
308}
309
310string Keymaster1Test::ProcessMessage(keymaster_purpose_t purpose, const string& message) {
311    EXPECT_EQ(KM_ERROR_OK, BeginOperation(purpose, client_params(), NULL /* output_params */));
312
313    string result;
314    size_t input_consumed;
315    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
316    EXPECT_EQ(message.size(), input_consumed);
317    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&result));
318    return result;
319}
320
321string Keymaster1Test::ProcessMessage(keymaster_purpose_t purpose, const string& message,
322                                      const AuthorizationSet& begin_params,
323                                      const AuthorizationSet& update_params,
324                                      AuthorizationSet* begin_out_params) {
325    EXPECT_EQ(KM_ERROR_OK, BeginOperation(purpose, begin_params, begin_out_params));
326
327    string result;
328    size_t input_consumed;
329    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, nullptr /* output_params */,
330                                           &result, &input_consumed));
331    EXPECT_EQ(message.size(), input_consumed);
332    EXPECT_EQ(KM_ERROR_OK, FinishOperation(update_params, "", &result));
333    return result;
334}
335
336string Keymaster1Test::ProcessMessage(keymaster_purpose_t purpose, const string& message,
337                                      const string& signature, const AuthorizationSet& begin_params,
338                                      const AuthorizationSet& update_params,
339                                      AuthorizationSet* output_params) {
340    EXPECT_EQ(KM_ERROR_OK, BeginOperation(purpose, begin_params, output_params));
341
342    string result;
343    size_t input_consumed;
344    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, nullptr /* output_params */,
345                                           &result, &input_consumed));
346    EXPECT_EQ(message.size(), input_consumed);
347    EXPECT_EQ(KM_ERROR_OK, FinishOperation(update_params, signature, &result));
348    return result;
349}
350
351string Keymaster1Test::ProcessMessage(keymaster_purpose_t purpose, const string& message,
352                                      const string& signature) {
353    EXPECT_EQ(KM_ERROR_OK, BeginOperation(purpose, client_params(), NULL /* output_params */));
354
355    string result;
356    size_t input_consumed;
357    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
358    EXPECT_EQ(message.size(), input_consumed);
359    EXPECT_EQ(KM_ERROR_OK, FinishOperation(signature, &result));
360    return result;
361}
362
363void Keymaster1Test::SignMessage(const string& message, string* signature,
364                                 keymaster_digest_t digest) {
365    SCOPED_TRACE("SignMessage");
366    AuthorizationSet input_params(AuthorizationSet(client_params_, array_length(client_params_)));
367    input_params.push_back(TAG_DIGEST, digest);
368    AuthorizationSet update_params;
369    AuthorizationSet output_params;
370    *signature =
371        ProcessMessage(KM_PURPOSE_SIGN, message, input_params, update_params, &output_params);
372    EXPECT_GT(signature->size(), 0U);
373}
374
375void Keymaster1Test::SignMessage(const string& message, string* signature,
376                                 keymaster_digest_t digest, keymaster_padding_t padding) {
377    SCOPED_TRACE("SignMessage");
378    AuthorizationSet input_params(AuthorizationSet(client_params_, array_length(client_params_)));
379    input_params.push_back(TAG_DIGEST, digest);
380    input_params.push_back(TAG_PADDING, padding);
381    AuthorizationSet update_params;
382    AuthorizationSet output_params;
383    *signature =
384        ProcessMessage(KM_PURPOSE_SIGN, message, input_params, update_params, &output_params);
385    EXPECT_GT(signature->size(), 0U);
386}
387
388void Keymaster1Test::MacMessage(const string& message, string* signature, size_t mac_length) {
389    SCOPED_TRACE("SignMessage");
390    AuthorizationSet input_params(AuthorizationSet(client_params_, array_length(client_params_)));
391    input_params.push_back(TAG_MAC_LENGTH, mac_length);
392    AuthorizationSet update_params;
393    AuthorizationSet output_params;
394    *signature =
395        ProcessMessage(KM_PURPOSE_SIGN, message, input_params, update_params, &output_params);
396    EXPECT_GT(signature->size(), 0U);
397}
398
399void Keymaster1Test::VerifyMessage(const string& message, const string& signature,
400                                   keymaster_digest_t digest) {
401    SCOPED_TRACE("VerifyMessage");
402    AuthorizationSet input_params(client_params());
403    input_params.push_back(TAG_DIGEST, digest);
404    AuthorizationSet update_params;
405    AuthorizationSet output_params;
406    ProcessMessage(KM_PURPOSE_VERIFY, message, signature, input_params, update_params,
407                   &output_params);
408}
409
410void Keymaster1Test::VerifyMessage(const string& message, const string& signature,
411                                   keymaster_digest_t digest, keymaster_padding_t padding) {
412    SCOPED_TRACE("VerifyMessage");
413    AuthorizationSet input_params(client_params());
414    input_params.push_back(TAG_DIGEST, digest);
415    input_params.push_back(TAG_PADDING, padding);
416    AuthorizationSet update_params;
417    AuthorizationSet output_params;
418    ProcessMessage(KM_PURPOSE_VERIFY, message, signature, input_params, update_params,
419                   &output_params);
420}
421
422void Keymaster1Test::VerifyMac(const string& message, const string& signature) {
423    SCOPED_TRACE("VerifyMac");
424    ProcessMessage(KM_PURPOSE_VERIFY, message, signature);
425}
426
427string Keymaster1Test::EncryptMessage(const string& message, keymaster_padding_t padding,
428                                      string* generated_nonce) {
429    SCOPED_TRACE("EncryptMessage");
430    AuthorizationSet begin_params(client_params()), output_params;
431    begin_params.push_back(TAG_PADDING, padding);
432    AuthorizationSet update_params;
433    string ciphertext =
434        ProcessMessage(KM_PURPOSE_ENCRYPT, message, begin_params, update_params, &output_params);
435    if (generated_nonce) {
436        keymaster_blob_t nonce_blob;
437        EXPECT_TRUE(output_params.GetTagValue(TAG_NONCE, &nonce_blob));
438        *generated_nonce = make_string(nonce_blob.data, nonce_blob.data_length);
439    } else {
440        EXPECT_EQ(-1, output_params.find(TAG_NONCE));
441    }
442    return ciphertext;
443}
444
445string Keymaster1Test::EncryptMessage(const string& message, keymaster_digest_t digest,
446                                      keymaster_padding_t padding, string* generated_nonce) {
447    AuthorizationSet update_params;
448    return EncryptMessage(update_params, message, digest, padding, generated_nonce);
449}
450
451string Keymaster1Test::EncryptMessage(const string& message, keymaster_block_mode_t block_mode,
452                                      keymaster_padding_t padding, string* generated_nonce) {
453    AuthorizationSet update_params;
454    return EncryptMessage(update_params, message, block_mode, padding, generated_nonce);
455}
456
457string Keymaster1Test::EncryptMessage(const AuthorizationSet& update_params, const string& message,
458                                      keymaster_digest_t digest, keymaster_padding_t padding,
459                                      string* generated_nonce) {
460    SCOPED_TRACE("EncryptMessage");
461    AuthorizationSet begin_params(client_params()), output_params;
462    begin_params.push_back(TAG_PADDING, padding);
463    begin_params.push_back(TAG_DIGEST, digest);
464    string ciphertext =
465        ProcessMessage(KM_PURPOSE_ENCRYPT, message, begin_params, update_params, &output_params);
466    if (generated_nonce) {
467        keymaster_blob_t nonce_blob;
468        EXPECT_TRUE(output_params.GetTagValue(TAG_NONCE, &nonce_blob));
469        *generated_nonce = make_string(nonce_blob.data, nonce_blob.data_length);
470    } else {
471        EXPECT_EQ(-1, output_params.find(TAG_NONCE));
472    }
473    return ciphertext;
474}
475
476string Keymaster1Test::EncryptMessage(const AuthorizationSet& update_params, const string& message,
477                                      keymaster_block_mode_t block_mode,
478                                      keymaster_padding_t padding, string* generated_nonce) {
479    SCOPED_TRACE("EncryptMessage");
480    AuthorizationSet begin_params(client_params()), output_params;
481    begin_params.push_back(TAG_PADDING, padding);
482    begin_params.push_back(TAG_BLOCK_MODE, block_mode);
483    string ciphertext =
484        ProcessMessage(KM_PURPOSE_ENCRYPT, message, begin_params, update_params, &output_params);
485    if (generated_nonce) {
486        keymaster_blob_t nonce_blob;
487        EXPECT_TRUE(output_params.GetTagValue(TAG_NONCE, &nonce_blob));
488        *generated_nonce = make_string(nonce_blob.data, nonce_blob.data_length);
489    } else {
490        EXPECT_EQ(-1, output_params.find(TAG_NONCE));
491    }
492    return ciphertext;
493}
494
495string Keymaster1Test::EncryptMessageWithParams(const string& message,
496                                                const AuthorizationSet& begin_params,
497                                                const AuthorizationSet& update_params,
498                                                AuthorizationSet* output_params) {
499    SCOPED_TRACE("EncryptMessageWithParams");
500    return ProcessMessage(KM_PURPOSE_ENCRYPT, message, begin_params, update_params, output_params);
501}
502
503string Keymaster1Test::DecryptMessage(const string& ciphertext, keymaster_padding_t padding) {
504    SCOPED_TRACE("DecryptMessage");
505    AuthorizationSet begin_params(client_params());
506    begin_params.push_back(TAG_PADDING, padding);
507    AuthorizationSet update_params;
508    return ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext, begin_params, update_params);
509}
510
511string Keymaster1Test::DecryptMessage(const string& ciphertext, keymaster_digest_t digest,
512                                      keymaster_padding_t padding) {
513    SCOPED_TRACE("DecryptMessage");
514    AuthorizationSet begin_params(client_params());
515    begin_params.push_back(TAG_PADDING, padding);
516    begin_params.push_back(TAG_DIGEST, digest);
517    AuthorizationSet update_params;
518    return ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext, begin_params, update_params);
519}
520
521string Keymaster1Test::DecryptMessage(const string& ciphertext, keymaster_block_mode_t block_mode,
522                                      keymaster_padding_t padding) {
523    SCOPED_TRACE("DecryptMessage");
524    AuthorizationSet begin_params(client_params());
525    begin_params.push_back(TAG_PADDING, padding);
526    begin_params.push_back(TAG_BLOCK_MODE, block_mode);
527    AuthorizationSet update_params;
528    return ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext, begin_params, update_params);
529}
530
531string Keymaster1Test::DecryptMessage(const string& ciphertext, keymaster_digest_t digest,
532                                      keymaster_padding_t padding, const string& nonce) {
533    SCOPED_TRACE("DecryptMessage");
534    AuthorizationSet begin_params(client_params());
535    begin_params.push_back(TAG_PADDING, padding);
536    begin_params.push_back(TAG_DIGEST, digest);
537    begin_params.push_back(TAG_NONCE, nonce.data(), nonce.size());
538    AuthorizationSet update_params;
539    return ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext, begin_params, update_params);
540}
541
542string Keymaster1Test::DecryptMessage(const string& ciphertext, keymaster_block_mode_t block_mode,
543                                      keymaster_padding_t padding, const string& nonce) {
544    SCOPED_TRACE("DecryptMessage");
545    AuthorizationSet begin_params(client_params());
546    begin_params.push_back(TAG_PADDING, padding);
547    begin_params.push_back(TAG_BLOCK_MODE, block_mode);
548    begin_params.push_back(TAG_NONCE, nonce.data(), nonce.size());
549    AuthorizationSet update_params;
550    return ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext, begin_params, update_params);
551}
552
553string Keymaster1Test::DecryptMessage(const AuthorizationSet& update_params,
554                                      const string& ciphertext, keymaster_digest_t digest,
555                                      keymaster_padding_t padding, const string& nonce) {
556    SCOPED_TRACE("DecryptMessage");
557    AuthorizationSet begin_params(client_params());
558    begin_params.push_back(TAG_PADDING, padding);
559    begin_params.push_back(TAG_DIGEST, digest);
560    begin_params.push_back(TAG_NONCE, nonce.data(), nonce.size());
561    return ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext, begin_params, update_params);
562}
563
564keymaster_error_t Keymaster1Test::GetCharacteristics() {
565    FreeCharacteristics();
566    return device()->get_key_characteristics(device(), &blob_, &client_id_, NULL /* app_data */,
567                                             &characteristics_);
568}
569
570keymaster_error_t Keymaster1Test::ExportKey(keymaster_key_format_t format, string* export_data) {
571    keymaster_blob_t export_tmp;
572    keymaster_error_t error = device()->export_key(device(), format, &blob_, &client_id_,
573                                                   NULL /* app_data */, &export_tmp);
574
575    if (error != KM_ERROR_OK)
576        return error;
577
578    *export_data = string(reinterpret_cast<const char*>(export_tmp.data), export_tmp.data_length);
579    free((void*)export_tmp.data);
580    return error;
581}
582
583void Keymaster1Test::CheckHmacTestVector(string key, string message, keymaster_digest_t digest,
584                                         string expected_mac) {
585    ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
586                                         .HmacKey(key.size() * 8)
587                                         .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
588                                         .Digest(digest),
589                                     KM_KEY_FORMAT_RAW, key));
590    string signature;
591    MacMessage(message, &signature, expected_mac.size() * 8);
592    EXPECT_EQ(expected_mac, signature) << "Test vector didn't match for digest " << (int)digest;
593}
594
595void Keymaster1Test::CheckAesCtrTestVector(const string& key, const string& nonce,
596                                           const string& message,
597                                           const string& expected_ciphertext) {
598    ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
599                                         .AesEncryptionKey(key.size() * 8)
600                                         .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
601                                         .Authorization(TAG_CALLER_NONCE)
602                                         .Padding(KM_PAD_NONE),
603                                     KM_KEY_FORMAT_RAW, key));
604
605    AuthorizationSet begin_params(client_params()), update_params, output_params;
606    begin_params.push_back(TAG_NONCE, nonce.data(), nonce.size());
607    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
608    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
609    string ciphertext =
610        EncryptMessageWithParams(message, begin_params, update_params, &output_params);
611    EXPECT_EQ(expected_ciphertext, ciphertext);
612}
613
614AuthorizationSet Keymaster1Test::hw_enforced() {
615    EXPECT_TRUE(characteristics_ != NULL);
616    return AuthorizationSet(characteristics_->hw_enforced);
617}
618
619AuthorizationSet Keymaster1Test::sw_enforced() {
620    EXPECT_TRUE(characteristics_ != NULL);
621    return AuthorizationSet(characteristics_->sw_enforced);
622}
623
624void Keymaster1Test::FreeCharacteristics() {
625    keymaster_free_characteristics(characteristics_);
626    free(characteristics_);
627    characteristics_ = NULL;
628}
629
630void Keymaster1Test::FreeKeyBlob() {
631    free(const_cast<uint8_t*>(blob_.key_material));
632    blob_.key_material = NULL;
633}
634
635void Keymaster1Test::corrupt_key_blob() {
636    assert(blob_.key_material);
637    uint8_t* tmp = const_cast<uint8_t*>(blob_.key_material);
638    ++tmp[blob_.key_material_size / 2];
639}
640
641class Sha256OnlyWrapper {
642  public:
643    Sha256OnlyWrapper(const keymaster1_device_t* wrapped_device) : wrapped_device_(wrapped_device) {
644
645        new_module = *wrapped_device_->common.module;
646        new_module_name = std::string("SHA 256-only ") + wrapped_device_->common.module->name;
647        new_module.name = new_module_name.c_str();
648
649        memset(&device_, 0, sizeof(device_));
650        device_.common.module = &new_module;
651
652        device_.common.close = close_device;
653        device_.get_supported_algorithms = get_supported_algorithms;
654        device_.get_supported_block_modes = get_supported_block_modes;
655        device_.get_supported_padding_modes = get_supported_padding_modes;
656        device_.get_supported_digests = get_supported_digests;
657        device_.get_supported_import_formats = get_supported_import_formats;
658        device_.get_supported_export_formats = get_supported_export_formats;
659        device_.add_rng_entropy = add_rng_entropy;
660        device_.generate_key = generate_key;
661        device_.get_key_characteristics = get_key_characteristics;
662        device_.import_key = import_key;
663        device_.export_key = export_key;
664        device_.begin = begin;
665        device_.update = update;
666        device_.finish = finish;
667        device_.abort = abort;
668    }
669
670    keymaster1_device_t* keymaster_device() { return &device_; }
671
672    static bool is_supported(keymaster_digest_t digest) {
673        return digest == KM_DIGEST_NONE || digest == KM_DIGEST_SHA_2_256;
674    }
675
676    static bool all_digests_supported(const keymaster_key_param_set_t* params) {
677        for (size_t i = 0; i < params->length; ++i)
678            if (params->params[i].tag == TAG_DIGEST)
679                if (!is_supported(static_cast<keymaster_digest_t>(params->params[i].enumerated)))
680                    return false;
681        return true;
682    }
683
684    static const keymaster_key_param_t*
685    get_algorithm_param(const keymaster_key_param_set_t* params) {
686        keymaster_key_param_t* end = params->params + params->length;
687        auto alg_ptr = std::find_if(params->params, end, [](keymaster_key_param_t& p) {
688            return p.tag == KM_TAG_ALGORITHM;
689        });
690        if (alg_ptr == end)
691            return nullptr;
692        return alg_ptr;
693    }
694
695    static int close_device(hw_device_t* dev) {
696        Sha256OnlyWrapper* wrapper = reinterpret_cast<Sha256OnlyWrapper*>(dev);
697        const keymaster1_device_t* wrapped_device = wrapper->wrapped_device_;
698        delete wrapper;
699        return wrapped_device->common.close(const_cast<hw_device_t*>(&wrapped_device->common));
700    }
701
702    static const keymaster1_device_t* unwrap(const keymaster1_device_t* dev) {
703        return reinterpret_cast<const Sha256OnlyWrapper*>(dev)->wrapped_device_;
704    }
705
706    static keymaster_error_t get_supported_algorithms(const struct keymaster1_device* dev,
707                                                      keymaster_algorithm_t** algorithms,
708                                                      size_t* algorithms_length) {
709        return unwrap(dev)->get_supported_algorithms(unwrap(dev), algorithms, algorithms_length);
710    }
711    static keymaster_error_t get_supported_block_modes(const struct keymaster1_device* dev,
712                                                       keymaster_algorithm_t algorithm,
713                                                       keymaster_purpose_t purpose,
714                                                       keymaster_block_mode_t** modes,
715                                                       size_t* modes_length) {
716        return unwrap(dev)
717            ->get_supported_block_modes(unwrap(dev), algorithm, purpose, modes, modes_length);
718    }
719    static keymaster_error_t get_supported_padding_modes(const struct keymaster1_device* dev,
720                                                         keymaster_algorithm_t algorithm,
721                                                         keymaster_purpose_t purpose,
722                                                         keymaster_padding_t** modes,
723                                                         size_t* modes_length) {
724        return unwrap(dev)
725            ->get_supported_padding_modes(unwrap(dev), algorithm, purpose, modes, modes_length);
726    }
727
728    static keymaster_error_t get_supported_digests(const keymaster1_device_t* dev,
729                                                   keymaster_algorithm_t algorithm,
730                                                   keymaster_purpose_t purpose,
731                                                   keymaster_digest_t** digests,
732                                                   size_t* digests_length) {
733        keymaster_error_t error = unwrap(dev)->get_supported_digests(
734            unwrap(dev), algorithm, purpose, digests, digests_length);
735        if (error != KM_ERROR_OK)
736            return error;
737
738        std::vector<keymaster_digest_t> filtered_digests;
739        std::copy_if(*digests, *digests + *digests_length, std::back_inserter(filtered_digests),
740                     [](keymaster_digest_t digest) { return is_supported(digest); });
741
742        free(*digests);
743        *digests_length = filtered_digests.size();
744        *digests = reinterpret_cast<keymaster_digest_t*>(
745            malloc(*digests_length * sizeof(keymaster_digest_t)));
746        std::copy(filtered_digests.begin(), filtered_digests.end(), *digests);
747
748        return KM_ERROR_OK;
749    }
750
751    static keymaster_error_t get_supported_import_formats(const struct keymaster1_device* dev,
752                                                          keymaster_algorithm_t algorithm,
753                                                          keymaster_key_format_t** formats,
754                                                          size_t* formats_length) {
755        return unwrap(dev)
756            ->get_supported_import_formats(unwrap(dev), algorithm, formats, formats_length);
757    }
758    static keymaster_error_t get_supported_export_formats(const struct keymaster1_device* dev,
759                                                          keymaster_algorithm_t algorithm,
760                                                          keymaster_key_format_t** formats,
761                                                          size_t* formats_length) {
762        return unwrap(dev)
763            ->get_supported_export_formats(unwrap(dev), algorithm, formats, formats_length);
764    }
765    static keymaster_error_t add_rng_entropy(const struct keymaster1_device* dev,
766                                             const uint8_t* data, size_t data_length) {
767        return unwrap(dev)->add_rng_entropy(unwrap(dev), data, data_length);
768    }
769
770    static keymaster_error_t generate_key(const keymaster1_device_t* dev,
771                                          const keymaster_key_param_set_t* params,
772                                          keymaster_key_blob_t* key_blob,
773                                          keymaster_key_characteristics_t** characteristics) {
774        auto alg_ptr = get_algorithm_param(params);
775        if (!alg_ptr)
776            return KM_ERROR_UNSUPPORTED_ALGORITHM;
777        if (alg_ptr->enumerated == KM_ALGORITHM_HMAC && !all_digests_supported(params))
778            return KM_ERROR_UNSUPPORTED_DIGEST;
779
780        return unwrap(dev)->generate_key(unwrap(dev), params, key_blob, characteristics);
781    }
782
783    static keymaster_error_t
784    get_key_characteristics(const struct keymaster1_device* dev,
785                            const keymaster_key_blob_t* key_blob, const keymaster_blob_t* client_id,
786                            const keymaster_blob_t* app_data,
787                            keymaster_key_characteristics_t** characteristics) {
788        return unwrap(dev)
789            ->get_key_characteristics(unwrap(dev), key_blob, client_id, app_data, characteristics);
790    }
791
792    static keymaster_error_t
793    import_key(const keymaster1_device_t* dev, const keymaster_key_param_set_t* params,
794               keymaster_key_format_t key_format, const keymaster_blob_t* key_data,
795               keymaster_key_blob_t* key_blob, keymaster_key_characteristics_t** characteristics) {
796        auto alg_ptr = get_algorithm_param(params);
797        if (!alg_ptr)
798            return KM_ERROR_UNSUPPORTED_ALGORITHM;
799        if (alg_ptr->enumerated == KM_ALGORITHM_HMAC && !all_digests_supported(params))
800            return KM_ERROR_UNSUPPORTED_DIGEST;
801
802        return unwrap(dev)
803            ->import_key(unwrap(dev), params, key_format, key_data, key_blob, characteristics);
804    }
805
806    static keymaster_error_t export_key(const struct keymaster1_device* dev,  //
807                                        keymaster_key_format_t export_format,
808                                        const keymaster_key_blob_t* key_to_export,
809                                        const keymaster_blob_t* client_id,
810                                        const keymaster_blob_t* app_data,
811                                        keymaster_blob_t* export_data) {
812        return unwrap(dev)->export_key(unwrap(dev), export_format, key_to_export, client_id,
813                                       app_data, export_data);
814    }
815
816    static keymaster_error_t begin(const keymaster1_device_t* dev,  //
817                                   keymaster_purpose_t purpose, const keymaster_key_blob_t* key,
818                                   const keymaster_key_param_set_t* in_params,
819                                   keymaster_key_param_set_t* out_params,
820                                   keymaster_operation_handle_t* operation_handle) {
821        if (!all_digests_supported(in_params))
822            return KM_ERROR_UNSUPPORTED_DIGEST;
823        return unwrap(dev)
824            ->begin(unwrap(dev), purpose, key, in_params, out_params, operation_handle);
825    }
826
827    static keymaster_error_t update(const keymaster1_device_t* dev,
828                                    keymaster_operation_handle_t operation_handle,
829                                    const keymaster_key_param_set_t* in_params,
830                                    const keymaster_blob_t* input, size_t* input_consumed,
831                                    keymaster_key_param_set_t* out_params,
832                                    keymaster_blob_t* output) {
833        return unwrap(dev)->update(unwrap(dev), operation_handle, in_params, input, input_consumed,
834                                   out_params, output);
835    }
836
837    static keymaster_error_t finish(const struct keymaster1_device* dev,  //
838                                    keymaster_operation_handle_t operation_handle,
839                                    const keymaster_key_param_set_t* in_params,
840                                    const keymaster_blob_t* signature,
841                                    keymaster_key_param_set_t* out_params,
842                                    keymaster_blob_t* output) {
843        return unwrap(dev)
844            ->finish(unwrap(dev), operation_handle, in_params, signature, out_params, output);
845    }
846
847    static keymaster_error_t abort(const struct keymaster1_device* dev,
848                                   keymaster_operation_handle_t operation_handle) {
849        return unwrap(dev)->abort(unwrap(dev), operation_handle);
850    }
851
852  private:
853    keymaster1_device_t device_;
854    const keymaster1_device_t* wrapped_device_;
855    hw_module_t new_module;
856    string new_module_name;
857};
858
859keymaster1_device_t* make_device_sha256_only(keymaster1_device_t* device) {
860    return (new Sha256OnlyWrapper(device))->keymaster_device();
861}
862
863}  // namespace test
864}  // namespace keymaster
865