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