android_keymaster_test.cpp revision b492f7082a7a95dc9360f40ea829c458f5d0b5a9
1/*
2 * Copyright (C) 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 <fstream>
18#include <string>
19#include <vector>
20
21#include <openssl/evp.h>
22#include <openssl/x509.h>
23
24#include <hardware/keymaster0.h>
25#include <keymaster/key_factory.h>
26#include <keymaster/soft_keymaster_context.h>
27#include <keymaster/soft_keymaster_device.h>
28#include <keymaster/softkeymaster.h>
29
30#include "android_keymaster_test_utils.h"
31#include "keymaster0_engine.h"
32#include "openssl_utils.h"
33
34using std::ifstream;
35using std::istreambuf_iterator;
36using std::string;
37using std::vector;
38using std::unique_ptr;
39
40extern "C" {
41int __android_log_print(int prio, const char* tag, const char* fmt);
42int __android_log_print(int prio, const char* tag, const char* fmt) {
43    (void)prio, (void)tag, (void)fmt;
44    return 0;
45}
46}  // extern "C"
47
48namespace keymaster {
49namespace test {
50
51StdoutLogger logger;
52
53template <typename T> vector<T> make_vector(const T* array, size_t len) {
54    return vector<T>(array, array + len);
55}
56
57/**
58 * KeymasterEnforcement class for use in testing.  It's permissive in the sense that it doesn't
59 * check cryptoperiods, but restrictive in the sense that the clock never advances (so rate-limited
60 * keys will only work once).
61 */
62class TestKeymasterEnforcement : public KeymasterEnforcement {
63  public:
64    TestKeymasterEnforcement() : KeymasterEnforcement(3, 3) {}
65
66    virtual bool activation_date_valid(uint64_t /* activation_date */) const { return true; }
67    virtual bool expiration_date_passed(uint64_t /* expiration_date */) const { return false; }
68    virtual bool auth_token_timed_out(const hw_auth_token_t& /* token */,
69                                      uint32_t /* timeout */) const {
70        return false;
71    }
72    virtual uint32_t get_current_time() const { return 0; }
73    virtual bool ValidateTokenSignature(const hw_auth_token_t& /* token */) const { return true; }
74};
75
76/**
77 * Variant of SoftKeymasterContext that provides a TestKeymasterEnforcement.
78 */
79class TestKeymasterContext : public SoftKeymasterContext {
80  public:
81    TestKeymasterContext() {}
82    TestKeymasterContext(const string& root_of_trust) : SoftKeymasterContext(root_of_trust) {}
83
84    KeymasterEnforcement* enforcement_policy() override { return &test_policy_; }
85
86  private:
87    TestKeymasterEnforcement test_policy_;
88};
89
90/**
91 * Test instance creator that builds a pure software keymaster1 implementations.
92 */
93class SoftKeymasterTestInstanceCreator : public Keymaster1TestInstanceCreator {
94  public:
95    keymaster1_device_t* CreateDevice() const override {
96        std::cerr << "Creating software-only device" << std::endl;
97        SoftKeymasterDevice* device = new SoftKeymasterDevice(new TestKeymasterContext);
98        return device->keymaster_device();
99    }
100
101    bool algorithm_in_km0_hardware(keymaster_algorithm_t) const override { return false; }
102    int keymaster0_calls() const override { return 0; }
103};
104
105/**
106 * Test instance creator that builds keymaster1 instances which wrap a faked hardware keymaster0
107 * instance, with or without EC support.
108 */
109class Keymaster0AdapterTestInstanceCreator : public Keymaster1TestInstanceCreator {
110  public:
111    Keymaster0AdapterTestInstanceCreator(bool support_ec) : support_ec_(support_ec) {}
112
113    keymaster1_device_t* CreateDevice() const {
114        std::cerr << "Creating keymaster0-backed device (with ec: " << std::boolalpha << support_ec_
115                  << ")." << std::endl;
116        hw_device_t* softkeymaster_device;
117        EXPECT_EQ(0, openssl_open(&softkeymaster_module.common, KEYSTORE_KEYMASTER,
118                                  &softkeymaster_device));
119        // Make the software device pretend to be hardware
120        keymaster0_device_t* keymaster0_device =
121            reinterpret_cast<keymaster0_device_t*>(softkeymaster_device);
122        keymaster0_device->flags &= ~KEYMASTER_SOFTWARE_ONLY;
123
124        if (!support_ec_) {
125            // Make the software device pretend not to support EC
126            keymaster0_device->flags &= ~KEYMASTER_SUPPORTS_EC;
127        }
128
129        counting_keymaster0_device_ = new Keymaster0CountingWrapper(keymaster0_device);
130
131        SoftKeymasterDevice* keymaster = new SoftKeymasterDevice(new TestKeymasterContext);
132        keymaster->SetHardwareDevice(counting_keymaster0_device_);
133        return keymaster->keymaster_device();
134    }
135
136    bool algorithm_in_km0_hardware(keymaster_algorithm_t algorithm) const override {
137        switch (algorithm) {
138        case KM_ALGORITHM_RSA:
139            return true;
140        case KM_ALGORITHM_EC:
141            return support_ec_;
142        default:
143            return false;
144        }
145    }
146    int keymaster0_calls() const override { return counting_keymaster0_device_->count(); }
147
148  private:
149    mutable Keymaster0CountingWrapper* counting_keymaster0_device_;
150    bool support_ec_;
151};
152
153/**
154 * Test instance creator that builds a SoftKeymasterDevice which wraps a fake hardware keymaster1
155 * instance, with minimal digest support.
156 */
157class Sha256OnlyKeymaster1TestInstanceCreator : public Keymaster1TestInstanceCreator {
158    keymaster1_device_t* CreateDevice() const {
159        std::cerr << "Creating keymaster1-backed device that supports only SHA256";
160
161        // fake_device doesn't leak because device (below) takes ownership of it.
162        keymaster1_device_t* fake_device = make_device_sha256_only(
163            (new SoftKeymasterDevice(new TestKeymasterContext("PseudoHW")))->keymaster_device());
164
165        // device doesn't leak; it's cleaned up by device->keymaster_device()->common.close().
166        SoftKeymasterDevice* device = new SoftKeymasterDevice(new TestKeymasterContext);
167        device->SetHardwareDevice(fake_device);
168
169        return device->keymaster_device();
170    }
171
172    bool algorithm_in_km0_hardware(keymaster_algorithm_t) const override { return false; }
173    int keymaster0_calls() const override { return 0; }
174    int minimal_digest_set() const override { return true; }
175};
176
177static auto test_params = testing::Values(
178    InstanceCreatorPtr(new SoftKeymasterTestInstanceCreator),
179    InstanceCreatorPtr(new Keymaster0AdapterTestInstanceCreator(true /* support_ec */)),
180    InstanceCreatorPtr(new Keymaster0AdapterTestInstanceCreator(false /* support_ec */)),
181    InstanceCreatorPtr(new Sha256OnlyKeymaster1TestInstanceCreator));
182
183typedef Keymaster1Test CheckSupported;
184INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, CheckSupported, test_params);
185
186TEST_P(CheckSupported, SupportedAlgorithms) {
187    EXPECT_EQ(KM_ERROR_OUTPUT_PARAMETER_NULL,
188              device()->get_supported_algorithms(device(), NULL, NULL));
189
190    size_t len;
191    keymaster_algorithm_t* algorithms;
192    EXPECT_EQ(KM_ERROR_OK, device()->get_supported_algorithms(device(), &algorithms, &len));
193    EXPECT_TRUE(ResponseContains(
194        {KM_ALGORITHM_RSA, KM_ALGORITHM_EC, KM_ALGORITHM_AES, KM_ALGORITHM_HMAC}, algorithms, len));
195    free(algorithms);
196
197    EXPECT_EQ(0, GetParam()->keymaster0_calls());
198}
199
200TEST_P(CheckSupported, SupportedBlockModes) {
201    EXPECT_EQ(KM_ERROR_OUTPUT_PARAMETER_NULL,
202              device()->get_supported_block_modes(device(), KM_ALGORITHM_RSA, KM_PURPOSE_ENCRYPT,
203                                                  NULL, NULL));
204
205    size_t len;
206    keymaster_block_mode_t* modes;
207    ASSERT_EQ(KM_ERROR_OK, device()->get_supported_block_modes(device(), KM_ALGORITHM_RSA,
208                                                               KM_PURPOSE_ENCRYPT, &modes, &len));
209    EXPECT_EQ(0U, len);
210    free(modes);
211
212    EXPECT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE,
213              device()->get_supported_block_modes(device(), KM_ALGORITHM_EC, KM_PURPOSE_ENCRYPT,
214                                                  &modes, &len));
215
216    ASSERT_EQ(KM_ERROR_OK, device()->get_supported_block_modes(device(), KM_ALGORITHM_AES,
217                                                               KM_PURPOSE_ENCRYPT, &modes, &len));
218    EXPECT_TRUE(ResponseContains({KM_MODE_ECB, KM_MODE_CBC, KM_MODE_CTR, KM_MODE_GCM}, modes, len));
219    free(modes);
220
221    EXPECT_EQ(0, GetParam()->keymaster0_calls());
222}
223
224TEST_P(CheckSupported, SupportedPaddingModes) {
225    EXPECT_EQ(KM_ERROR_OUTPUT_PARAMETER_NULL,
226              device()->get_supported_padding_modes(device(), KM_ALGORITHM_RSA, KM_PURPOSE_ENCRYPT,
227                                                    NULL, NULL));
228
229    size_t len;
230    keymaster_padding_t* modes;
231    ASSERT_EQ(KM_ERROR_OK, device()->get_supported_padding_modes(device(), KM_ALGORITHM_RSA,
232                                                                 KM_PURPOSE_SIGN, &modes, &len));
233    EXPECT_TRUE(
234        ResponseContains({KM_PAD_NONE, KM_PAD_RSA_PKCS1_1_5_SIGN, KM_PAD_RSA_PSS}, modes, len));
235    free(modes);
236
237    ASSERT_EQ(KM_ERROR_OK, device()->get_supported_padding_modes(device(), KM_ALGORITHM_RSA,
238                                                                 KM_PURPOSE_ENCRYPT, &modes, &len));
239    EXPECT_TRUE(
240        ResponseContains({KM_PAD_NONE, KM_PAD_RSA_OAEP, KM_PAD_RSA_PKCS1_1_5_ENCRYPT}, modes, len));
241    free(modes);
242
243    ASSERT_EQ(KM_ERROR_OK, device()->get_supported_padding_modes(device(), KM_ALGORITHM_EC,
244                                                                 KM_PURPOSE_SIGN, &modes, &len));
245    EXPECT_EQ(0U, len);
246    free(modes);
247
248    EXPECT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE,
249              device()->get_supported_padding_modes(device(), KM_ALGORITHM_AES, KM_PURPOSE_SIGN,
250                                                    &modes, &len));
251
252    EXPECT_EQ(0, GetParam()->keymaster0_calls());
253}
254
255TEST_P(CheckSupported, SupportedDigests) {
256    EXPECT_EQ(
257        KM_ERROR_OUTPUT_PARAMETER_NULL,
258        device()->get_supported_digests(device(), KM_ALGORITHM_RSA, KM_PURPOSE_SIGN, NULL, NULL));
259
260    size_t len;
261    keymaster_digest_t* digests;
262    ASSERT_EQ(KM_ERROR_OK, device()->get_supported_digests(device(), KM_ALGORITHM_RSA,
263                                                           KM_PURPOSE_SIGN, &digests, &len));
264    if (GetParam()->minimal_digest_set()) {
265        EXPECT_TRUE(ResponseContains({KM_DIGEST_NONE, KM_DIGEST_SHA_2_256}, digests, len));
266    } else {
267        EXPECT_TRUE(
268            ResponseContains({KM_DIGEST_NONE, KM_DIGEST_MD5, KM_DIGEST_SHA1, KM_DIGEST_SHA_2_224,
269                              KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512},
270                             digests, len));
271    }
272    free(digests);
273
274    ASSERT_EQ(KM_ERROR_OK, device()->get_supported_digests(device(), KM_ALGORITHM_RSA,
275                                                           KM_PURPOSE_ENCRYPT, &digests, &len));
276    if (GetParam()->minimal_digest_set()) {
277        EXPECT_TRUE(ResponseContains({KM_DIGEST_NONE, KM_DIGEST_SHA_2_256}, digests, len));
278    } else {
279        EXPECT_TRUE(
280            ResponseContains({KM_DIGEST_NONE, KM_DIGEST_MD5, KM_DIGEST_SHA1, KM_DIGEST_SHA_2_224,
281                              KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512},
282                             digests, len));
283    }
284    free(digests);
285
286    ASSERT_EQ(KM_ERROR_OK, device()->get_supported_digests(device(), KM_ALGORITHM_EC,
287                                                           KM_PURPOSE_SIGN, &digests, &len));
288    if (GetParam()->minimal_digest_set()) {
289        EXPECT_TRUE(ResponseContains({KM_DIGEST_NONE, KM_DIGEST_SHA_2_256}, digests, len));
290    } else {
291        EXPECT_TRUE(
292            ResponseContains({KM_DIGEST_NONE, KM_DIGEST_SHA1, KM_DIGEST_SHA_2_224,
293                              KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512},
294                             digests, len));
295    }
296    free(digests);
297
298    EXPECT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE,
299              device()->get_supported_digests(device(), KM_ALGORITHM_AES, KM_PURPOSE_SIGN, &digests,
300                                              &len));
301
302    ASSERT_EQ(KM_ERROR_OK, device()->get_supported_digests(device(), KM_ALGORITHM_HMAC,
303                                                           KM_PURPOSE_SIGN, &digests, &len));
304    if (GetParam()->minimal_digest_set()) {
305        EXPECT_TRUE(ResponseContains(KM_DIGEST_SHA_2_256, digests, len));
306    } else {
307        EXPECT_TRUE(ResponseContains({KM_DIGEST_SHA_2_224, KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384,
308                                      KM_DIGEST_SHA_2_512, KM_DIGEST_SHA1},
309                                     digests, len));
310    }
311    free(digests);
312
313    EXPECT_EQ(0, GetParam()->keymaster0_calls());
314}
315
316TEST_P(CheckSupported, SupportedImportFormats) {
317    EXPECT_EQ(KM_ERROR_OUTPUT_PARAMETER_NULL,
318              device()->get_supported_import_formats(device(), KM_ALGORITHM_RSA, NULL, NULL));
319
320    size_t len;
321    keymaster_key_format_t* formats;
322    ASSERT_EQ(KM_ERROR_OK,
323              device()->get_supported_import_formats(device(), KM_ALGORITHM_RSA, &formats, &len));
324    EXPECT_TRUE(ResponseContains(KM_KEY_FORMAT_PKCS8, formats, len));
325    free(formats);
326
327    ASSERT_EQ(KM_ERROR_OK,
328              device()->get_supported_import_formats(device(), KM_ALGORITHM_AES, &formats, &len));
329    EXPECT_TRUE(ResponseContains(KM_KEY_FORMAT_RAW, formats, len));
330    free(formats);
331
332    ASSERT_EQ(KM_ERROR_OK,
333              device()->get_supported_import_formats(device(), KM_ALGORITHM_HMAC, &formats, &len));
334    EXPECT_TRUE(ResponseContains(KM_KEY_FORMAT_RAW, formats, len));
335    free(formats);
336
337    EXPECT_EQ(0, GetParam()->keymaster0_calls());
338}
339
340TEST_P(CheckSupported, SupportedExportFormats) {
341    EXPECT_EQ(KM_ERROR_OUTPUT_PARAMETER_NULL,
342              device()->get_supported_export_formats(device(), KM_ALGORITHM_RSA, NULL, NULL));
343
344    size_t len;
345    keymaster_key_format_t* formats;
346    ASSERT_EQ(KM_ERROR_OK,
347              device()->get_supported_export_formats(device(), KM_ALGORITHM_RSA, &formats, &len));
348    EXPECT_TRUE(ResponseContains(KM_KEY_FORMAT_X509, formats, len));
349    free(formats);
350
351    ASSERT_EQ(KM_ERROR_OK,
352              device()->get_supported_export_formats(device(), KM_ALGORITHM_EC, &formats, &len));
353    EXPECT_TRUE(ResponseContains(KM_KEY_FORMAT_X509, formats, len));
354    free(formats);
355
356    ASSERT_EQ(KM_ERROR_OK,
357              device()->get_supported_export_formats(device(), KM_ALGORITHM_AES, &formats, &len));
358    EXPECT_EQ(0U, len);
359    free(formats);
360
361    ASSERT_EQ(KM_ERROR_OK,
362              device()->get_supported_export_formats(device(), KM_ALGORITHM_AES, &formats, &len));
363    EXPECT_EQ(0U, len);
364    free(formats);
365
366    ASSERT_EQ(KM_ERROR_OK,
367              device()->get_supported_export_formats(device(), KM_ALGORITHM_HMAC, &formats, &len));
368    EXPECT_EQ(0U, len);
369    free(formats);
370
371    EXPECT_EQ(0, GetParam()->keymaster0_calls());
372}
373
374class NewKeyGeneration : public Keymaster1Test {
375  protected:
376    void CheckBaseParams() {
377        AuthorizationSet auths = sw_enforced();
378        EXPECT_GT(auths.SerializedSize(), 12U);
379
380        EXPECT_TRUE(contains(auths, TAG_PURPOSE, KM_PURPOSE_SIGN));
381        EXPECT_TRUE(contains(auths, TAG_PURPOSE, KM_PURPOSE_VERIFY));
382        EXPECT_TRUE(contains(auths, TAG_USER_ID, 7));
383        EXPECT_TRUE(contains(auths, TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD));
384        EXPECT_TRUE(contains(auths, TAG_AUTH_TIMEOUT, 300));
385
386        // Verify that App ID, App data and ROT are NOT included.
387        EXPECT_FALSE(contains(auths, TAG_ROOT_OF_TRUST));
388        EXPECT_FALSE(contains(auths, TAG_APPLICATION_ID));
389        EXPECT_FALSE(contains(auths, TAG_APPLICATION_DATA));
390
391        // Just for giggles, check that some unexpected tags/values are NOT present.
392        EXPECT_FALSE(contains(auths, TAG_PURPOSE, KM_PURPOSE_ENCRYPT));
393        EXPECT_FALSE(contains(auths, TAG_PURPOSE, KM_PURPOSE_DECRYPT));
394        EXPECT_FALSE(contains(auths, TAG_AUTH_TIMEOUT, 301));
395
396        // Now check that unspecified, defaulted tags are correct.
397        EXPECT_TRUE(contains(auths, KM_TAG_CREATION_DATETIME));
398    }
399};
400INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, NewKeyGeneration, test_params);
401
402TEST_P(NewKeyGeneration, Rsa) {
403    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
404                                           .RsaSigningKey(256, 3)
405                                           .Digest(KM_DIGEST_NONE)
406                                           .Padding(KM_PAD_NONE)));
407    CheckBaseParams();
408
409    // Check specified tags are all present, and in the right set.
410    AuthorizationSet crypto_params;
411    AuthorizationSet non_crypto_params;
412    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA)) {
413        EXPECT_NE(0U, hw_enforced().size());
414        EXPECT_NE(0U, sw_enforced().size());
415        crypto_params.push_back(hw_enforced());
416        non_crypto_params.push_back(sw_enforced());
417    } else {
418        EXPECT_EQ(0U, hw_enforced().size());
419        EXPECT_NE(0U, sw_enforced().size());
420        crypto_params.push_back(sw_enforced());
421    }
422
423    EXPECT_TRUE(contains(crypto_params, TAG_ALGORITHM, KM_ALGORITHM_RSA));
424    EXPECT_FALSE(contains(non_crypto_params, TAG_ALGORITHM, KM_ALGORITHM_RSA));
425    EXPECT_TRUE(contains(crypto_params, TAG_KEY_SIZE, 256));
426    EXPECT_FALSE(contains(non_crypto_params, TAG_KEY_SIZE, 256));
427    EXPECT_TRUE(contains(crypto_params, TAG_RSA_PUBLIC_EXPONENT, 3));
428    EXPECT_FALSE(contains(non_crypto_params, TAG_RSA_PUBLIC_EXPONENT, 3));
429
430    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
431        EXPECT_EQ(1, GetParam()->keymaster0_calls());
432}
433
434TEST_P(NewKeyGeneration, RsaDefaultSize) {
435    ASSERT_EQ(KM_ERROR_UNSUPPORTED_KEY_SIZE,
436              GenerateKey(AuthorizationSetBuilder()
437                              .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA)
438                              .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3)
439                              .SigningKey()));
440
441    EXPECT_EQ(0, GetParam()->keymaster0_calls());
442}
443
444TEST_P(NewKeyGeneration, Ecdsa) {
445    ASSERT_EQ(KM_ERROR_OK,
446              GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
447    CheckBaseParams();
448
449    // Check specified tags are all present, and in the right set.
450    AuthorizationSet crypto_params;
451    AuthorizationSet non_crypto_params;
452    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC)) {
453        EXPECT_NE(0U, hw_enforced().size());
454        EXPECT_NE(0U, sw_enforced().size());
455        crypto_params.push_back(hw_enforced());
456        non_crypto_params.push_back(sw_enforced());
457    } else {
458        EXPECT_EQ(0U, hw_enforced().size());
459        EXPECT_NE(0U, sw_enforced().size());
460        crypto_params.push_back(sw_enforced());
461    }
462
463    EXPECT_TRUE(contains(crypto_params, TAG_ALGORITHM, KM_ALGORITHM_EC));
464    EXPECT_FALSE(contains(non_crypto_params, TAG_ALGORITHM, KM_ALGORITHM_EC));
465    EXPECT_TRUE(contains(crypto_params, TAG_KEY_SIZE, 224));
466    EXPECT_FALSE(contains(non_crypto_params, TAG_KEY_SIZE, 224));
467
468    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
469        EXPECT_EQ(1, GetParam()->keymaster0_calls());
470}
471
472TEST_P(NewKeyGeneration, EcdsaDefaultSize) {
473    ASSERT_EQ(KM_ERROR_UNSUPPORTED_KEY_SIZE,
474              GenerateKey(AuthorizationSetBuilder()
475                              .Authorization(TAG_ALGORITHM, KM_ALGORITHM_EC)
476                              .SigningKey()
477                              .Digest(KM_DIGEST_NONE)));
478
479    EXPECT_EQ(0, GetParam()->keymaster0_calls());
480}
481
482TEST_P(NewKeyGeneration, EcdsaInvalidSize) {
483    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
484        ASSERT_EQ(
485            KM_ERROR_UNKNOWN_ERROR,
486            GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(190).Digest(KM_DIGEST_NONE)));
487    else
488        ASSERT_EQ(
489            KM_ERROR_UNSUPPORTED_KEY_SIZE,
490            GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(190).Digest(KM_DIGEST_NONE)));
491
492    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
493        EXPECT_EQ(1, GetParam()->keymaster0_calls());
494}
495
496TEST_P(NewKeyGeneration, EcdsaAllValidSizes) {
497    size_t valid_sizes[] = {224, 256, 384, 521};
498    for (size_t size : valid_sizes) {
499        EXPECT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(size).Digest(
500                                   KM_DIGEST_NONE)))
501            << "Failed to generate size: " << size;
502    }
503
504    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
505        EXPECT_EQ(4, GetParam()->keymaster0_calls());
506}
507
508TEST_P(NewKeyGeneration, HmacSha256) {
509    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
510                                           .HmacKey(128)
511                                           .Digest(KM_DIGEST_SHA_2_256)
512                                           .Authorization(TAG_MIN_MAC_LENGTH, 256)));
513
514    EXPECT_EQ(0, GetParam()->keymaster0_calls());
515}
516
517TEST_P(NewKeyGeneration, HmacMultipleDigests) {
518    ASSERT_EQ(KM_ERROR_UNSUPPORTED_DIGEST,
519              GenerateKey(AuthorizationSetBuilder()
520                              .HmacKey(128)
521                              .Digest(KM_DIGEST_SHA1)
522                              .Digest(KM_DIGEST_SHA_2_256)
523                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
524
525    EXPECT_EQ(0, GetParam()->keymaster0_calls());
526}
527
528TEST_P(NewKeyGeneration, HmacDigestNone) {
529    ASSERT_EQ(KM_ERROR_UNSUPPORTED_DIGEST,
530              GenerateKey(AuthorizationSetBuilder()
531                              .HmacKey(128)
532                              .Digest(KM_DIGEST_NONE)
533                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
534
535    EXPECT_EQ(0, GetParam()->keymaster0_calls());
536}
537
538TEST_P(NewKeyGeneration, HmacSha256TooShortMacLength) {
539    ASSERT_EQ(KM_ERROR_UNSUPPORTED_MIN_MAC_LENGTH,
540              GenerateKey(AuthorizationSetBuilder()
541                              .HmacKey(128)
542                              .Digest(KM_DIGEST_SHA_2_256)
543                              .Authorization(TAG_MIN_MAC_LENGTH, 48)));
544
545    EXPECT_EQ(0, GetParam()->keymaster0_calls());
546}
547
548TEST_P(NewKeyGeneration, HmacSha256NonIntegralOctetMacLength) {
549    ASSERT_EQ(KM_ERROR_UNSUPPORTED_MIN_MAC_LENGTH,
550              GenerateKey(AuthorizationSetBuilder()
551                              .HmacKey(128)
552                              .Digest(KM_DIGEST_SHA_2_256)
553                              .Authorization(TAG_MIN_MAC_LENGTH, 130)));
554
555    EXPECT_EQ(0, GetParam()->keymaster0_calls());
556}
557
558TEST_P(NewKeyGeneration, HmacSha256TooLongMacLength) {
559    ASSERT_EQ(KM_ERROR_UNSUPPORTED_MIN_MAC_LENGTH,
560              GenerateKey(AuthorizationSetBuilder()
561                              .HmacKey(128)
562                              .Digest(KM_DIGEST_SHA_2_256)
563                              .Authorization(TAG_MIN_MAC_LENGTH, 384)));
564
565    EXPECT_EQ(0, GetParam()->keymaster0_calls());
566}
567
568typedef Keymaster1Test GetKeyCharacteristics;
569INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, GetKeyCharacteristics, test_params);
570
571TEST_P(GetKeyCharacteristics, SimpleRsa) {
572    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
573                                           .RsaSigningKey(256, 3)
574                                           .Digest(KM_DIGEST_NONE)
575                                           .Padding(KM_PAD_NONE)));
576    AuthorizationSet original(sw_enforced());
577
578    ASSERT_EQ(KM_ERROR_OK, GetCharacteristics());
579    EXPECT_EQ(original, sw_enforced());
580
581    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
582        EXPECT_EQ(1, GetParam()->keymaster0_calls());
583}
584
585typedef Keymaster1Test SigningOperationsTest;
586INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, SigningOperationsTest, test_params);
587
588TEST_P(SigningOperationsTest, RsaSuccess) {
589    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
590                                           .RsaSigningKey(256, 3)
591                                           .Digest(KM_DIGEST_NONE)
592                                           .Padding(KM_PAD_NONE)));
593    string message = "12345678901234567890123456789012";
594    string signature;
595    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
596
597    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
598        EXPECT_EQ(3, GetParam()->keymaster0_calls());
599}
600
601TEST_P(SigningOperationsTest, RsaPssSha256Success) {
602    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
603                                           .RsaSigningKey(512, 3)
604                                           .Digest(KM_DIGEST_SHA_2_256)
605                                           .Padding(KM_PAD_RSA_PSS)));
606    // Use large message, which won't work without digesting.
607    string message(1024, 'a');
608    string signature;
609    SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
610
611    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
612        EXPECT_EQ(3, GetParam()->keymaster0_calls());
613}
614
615TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
616    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
617                                           .RsaSigningKey(512, 3)
618                                           .Digest(KM_DIGEST_NONE)
619                                           .Padding(KM_PAD_NONE)));
620    string message = "12345678901234567890123456789012";
621    string signature;
622
623    AuthorizationSet begin_params(client_params());
624    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
625    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
626    EXPECT_EQ(KM_ERROR_INCOMPATIBLE_PADDING_MODE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
627
628    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
629        EXPECT_EQ(2, GetParam()->keymaster0_calls());
630}
631
632TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
633    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
634                                           .RsaSigningKey(512, 3)
635                                           .Digest(KM_DIGEST_SHA_2_256)
636                                           .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
637    string message(1024, 'a');
638    string signature;
639    SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
640
641    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
642        EXPECT_EQ(3, GetParam()->keymaster0_calls());
643}
644
645TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
646    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
647                                           .RsaSigningKey(512, 3)
648                                           .Digest(KM_DIGEST_NONE)
649                                           .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
650    string message(53, 'a');
651    string signature;
652    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_RSA_PKCS1_1_5_SIGN);
653
654    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
655        EXPECT_EQ(3, GetParam()->keymaster0_calls());
656}
657
658TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLarge) {
659    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
660                                           .RsaSigningKey(512, 3)
661                                           .Digest(KM_DIGEST_NONE)
662                                           .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
663    string message(54, 'a');
664
665    AuthorizationSet begin_params(client_params());
666    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
667    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
668    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
669    string result;
670    size_t input_consumed;
671    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
672    string signature;
673    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(&signature));
674
675    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
676        EXPECT_EQ(2, GetParam()->keymaster0_calls());
677}
678
679TEST_P(SigningOperationsTest, RsaPssSha256TooSmallKey) {
680    // Key must be at least 10 bytes larger than hash, to provide eight bytes of random salt, so
681    // verify that nine bytes larger than hash won't work.
682    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
683                                           .RsaSigningKey(256 + 9 * 8, 3)
684                                           .Digest(KM_DIGEST_SHA_2_256)
685                                           .Padding(KM_PAD_RSA_PSS)));
686    string message(1024, 'a');
687    string signature;
688
689    AuthorizationSet begin_params(client_params());
690    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
691    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PSS);
692    EXPECT_EQ(KM_ERROR_INCOMPATIBLE_DIGEST, BeginOperation(KM_PURPOSE_SIGN, begin_params));
693}
694
695TEST_P(SigningOperationsTest, RsaNoPaddingHugeData) {
696    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
697                                           .RsaSigningKey(256, 3)
698                                           .Digest(KM_DIGEST_NONE)
699                                           .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
700    string message(64 * 1024, 'a');
701    string signature;
702    AuthorizationSet begin_params(client_params());
703    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
704    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
705    ASSERT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
706    string result;
707    size_t input_consumed;
708    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, UpdateOperation(message, &result, &input_consumed));
709
710    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
711        EXPECT_EQ(2, GetParam()->keymaster0_calls());
712}
713
714TEST_P(SigningOperationsTest, RsaAbort) {
715    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
716                                           .RsaSigningKey(256, 3)
717                                           .Digest(KM_DIGEST_NONE)
718                                           .Padding(KM_PAD_NONE)));
719    AuthorizationSet begin_params(client_params());
720    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
721    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
722    ASSERT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
723    EXPECT_EQ(KM_ERROR_OK, AbortOperation());
724    // Another abort should fail
725    EXPECT_EQ(KM_ERROR_INVALID_OPERATION_HANDLE, AbortOperation());
726
727    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
728        EXPECT_EQ(2, GetParam()->keymaster0_calls());
729}
730
731TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
732    GenerateKey(AuthorizationSetBuilder()
733                    .RsaSigningKey(256, 3)
734                    .Digest(KM_DIGEST_SHA_2_256 /* supported digest */)
735                    .Padding(KM_PAD_PKCS7));
736    AuthorizationSet begin_params(client_params());
737    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
738    ASSERT_EQ(KM_ERROR_UNSUPPORTED_PADDING_MODE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
739
740    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
741        EXPECT_EQ(2, GetParam()->keymaster0_calls());
742}
743
744TEST_P(SigningOperationsTest, RsaNoDigest) {
745    // PSS requires a digest.
746    GenerateKey(AuthorizationSetBuilder()
747                    .RsaSigningKey(256, 3)
748                    .Digest(KM_DIGEST_NONE)
749                    .Padding(KM_PAD_RSA_PSS));
750    AuthorizationSet begin_params(client_params());
751    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
752    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PSS);
753    ASSERT_EQ(KM_ERROR_INCOMPATIBLE_DIGEST, BeginOperation(KM_PURPOSE_SIGN, begin_params));
754
755    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
756        EXPECT_EQ(2, GetParam()->keymaster0_calls());
757}
758
759TEST_P(SigningOperationsTest, RsaNoPadding) {
760    // Padding must be specified
761    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaKey(256, 3).SigningKey().Digest(
762                               KM_DIGEST_NONE)));
763    AuthorizationSet begin_params(client_params());
764    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
765    ASSERT_EQ(KM_ERROR_UNSUPPORTED_PADDING_MODE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
766
767    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
768        EXPECT_EQ(2, GetParam()->keymaster0_calls());
769}
770
771TEST_P(SigningOperationsTest, RsaTooShortMessage) {
772    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
773                                           .RsaSigningKey(256, 3)
774                                           .Digest(KM_DIGEST_NONE)
775                                           .Padding(KM_PAD_NONE)));
776    string message = "1234567890123456789012345678901";
777    string signature;
778    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
779
780    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
781        EXPECT_EQ(3, GetParam()->keymaster0_calls());
782}
783
784TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
785    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
786                                           .RsaEncryptionKey(256, 3)
787                                           .Digest(KM_DIGEST_NONE)
788                                           .Padding(KM_PAD_NONE)));
789    AuthorizationSet begin_params(client_params());
790    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
791    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
792    ASSERT_EQ(KM_ERROR_INCOMPATIBLE_PURPOSE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
793
794    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
795        EXPECT_EQ(2, GetParam()->keymaster0_calls());
796}
797
798TEST_P(SigningOperationsTest, EcdsaSuccess) {
799    ASSERT_EQ(KM_ERROR_OK,
800              GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
801    string message(224 / 8, 'a');
802    string signature;
803    SignMessage(message, &signature, KM_DIGEST_NONE);
804
805    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
806        EXPECT_EQ(3, GetParam()->keymaster0_calls());
807}
808
809TEST_P(SigningOperationsTest, EcdsaSha256Success) {
810    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(
811                               KM_DIGEST_SHA_2_256)));
812    string message(1024, 'a');
813    string signature;
814    SignMessage(message, &signature, KM_DIGEST_SHA_2_256);
815
816    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
817        EXPECT_EQ(3, GetParam()->keymaster0_calls());
818}
819
820TEST_P(SigningOperationsTest, EcdsaSha384Success) {
821    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(
822                               KM_DIGEST_SHA_2_384)));
823    string message(1024, 'a');
824    string signature;
825    SignMessage(message, &signature, KM_DIGEST_SHA_2_384);
826
827    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
828        EXPECT_EQ(3, GetParam()->keymaster0_calls());
829}
830
831TEST_P(SigningOperationsTest, EcdsaNoPaddingHugeData) {
832    ASSERT_EQ(KM_ERROR_OK,
833              GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
834    string message(64 * 1024, 'a');
835    string signature;
836    AuthorizationSet begin_params(client_params());
837    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
838    ASSERT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
839    string result;
840    size_t input_consumed;
841    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
842
843    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
844        EXPECT_EQ(2, GetParam()->keymaster0_calls());
845}
846
847TEST_P(SigningOperationsTest, EcsdaAllSizesAndHashes) {
848    size_t len;
849    keymaster_digest_t* digest_arr;
850    ASSERT_EQ(KM_ERROR_OK, device()->get_supported_digests(device(), KM_ALGORITHM_EC,
851                                                           KM_PURPOSE_SIGN, &digest_arr, &len));
852    vector<int> key_sizes = {224, 256, 384, 521};
853    vector<keymaster_digest_t> digests = make_vector(digest_arr, len);
854    free(digest_arr);
855
856    for (int key_size : key_sizes) {
857        for (keymaster_digest_t digest : digests) {
858            ASSERT_EQ(
859                KM_ERROR_OK,
860                GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(key_size).Digest(digest)));
861
862            string message(1024, 'a');
863            string signature;
864            if (digest == KM_DIGEST_NONE)
865                message.resize(key_size / 8);
866            SignMessage(message, &signature, digest);
867        }
868    }
869
870    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
871        EXPECT_EQ(digests.size() * key_sizes.size() * 3,
872                  static_cast<size_t>(GetParam()->keymaster0_calls()));
873}
874
875TEST_P(SigningOperationsTest, AesEcbSign) {
876    ASSERT_EQ(KM_ERROR_OK,
877              GenerateKey(AuthorizationSetBuilder().AesEncryptionKey(128).Authorization(
878                  TAG_BLOCK_MODE, KM_MODE_ECB)));
879    ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_SIGN));
880    ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_VERIFY));
881
882    EXPECT_EQ(0, GetParam()->keymaster0_calls());
883}
884
885TEST_P(SigningOperationsTest, HmacSha1Success) {
886    if (GetParam()->minimal_digest_set())
887        // Can't emulate other digests for HMAC.
888        return;
889
890    GenerateKey(AuthorizationSetBuilder()
891                    .HmacKey(128)
892                    .Digest(KM_DIGEST_SHA1)
893                    .Authorization(TAG_MIN_MAC_LENGTH, 160));
894    string message = "12345678901234567890123456789012";
895    string signature;
896    MacMessage(message, &signature, 160);
897    ASSERT_EQ(20U, signature.size());
898
899    EXPECT_EQ(0, GetParam()->keymaster0_calls());
900}
901
902TEST_P(SigningOperationsTest, HmacSha224Success) {
903    if (GetParam()->minimal_digest_set())
904        // Can't emulate other digests for HMAC.
905        return;
906
907    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
908                                           .HmacKey(128)
909                                           .Digest(KM_DIGEST_SHA_2_224)
910                                           .Authorization(TAG_MIN_MAC_LENGTH, 160)));
911    string message = "12345678901234567890123456789012";
912    string signature;
913    MacMessage(message, &signature, 224);
914    ASSERT_EQ(28U, signature.size());
915
916    EXPECT_EQ(0, GetParam()->keymaster0_calls());
917}
918
919TEST_P(SigningOperationsTest, HmacSha256Success) {
920    if (GetParam()->minimal_digest_set())
921        // Can't emulate other digests for HMAC.
922        return;
923
924    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
925                                           .HmacKey(128)
926                                           .Digest(KM_DIGEST_SHA_2_256)
927                                           .Authorization(TAG_MIN_MAC_LENGTH, 256)));
928    string message = "12345678901234567890123456789012";
929    string signature;
930    MacMessage(message, &signature, 256);
931    ASSERT_EQ(32U, signature.size());
932
933    EXPECT_EQ(0, GetParam()->keymaster0_calls());
934}
935
936TEST_P(SigningOperationsTest, HmacSha384Success) {
937    if (GetParam()->minimal_digest_set())
938        // Can't emulate other digests for HMAC.
939        return;
940
941    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
942                                           .HmacKey(128)
943                                           .Digest(KM_DIGEST_SHA_2_384)
944                                           .Authorization(TAG_MIN_MAC_LENGTH, 384)));
945
946    string message = "12345678901234567890123456789012";
947    string signature;
948    MacMessage(message, &signature, 384);
949    ASSERT_EQ(48U, signature.size());
950
951    EXPECT_EQ(0, GetParam()->keymaster0_calls());
952}
953
954TEST_P(SigningOperationsTest, HmacSha512Success) {
955    if (GetParam()->minimal_digest_set())
956        // Can't emulate other digests for HMAC.
957        return;
958
959    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
960                                           .HmacKey(128)
961                                           .Digest(KM_DIGEST_SHA_2_512)
962                                           .Authorization(TAG_MIN_MAC_LENGTH, 384)));
963    string message = "12345678901234567890123456789012";
964    string signature;
965    MacMessage(message, &signature, 512);
966    ASSERT_EQ(64U, signature.size());
967
968    EXPECT_EQ(0, GetParam()->keymaster0_calls());
969}
970
971TEST_P(SigningOperationsTest, HmacLengthInKey) {
972    // TODO(swillden): unified API should generate an error on key generation.
973    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
974                                           .HmacKey(128)
975                                           .Digest(KM_DIGEST_SHA_2_256)
976                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)));
977    string message = "12345678901234567890123456789012";
978    string signature;
979    MacMessage(message, &signature, 160);
980    ASSERT_EQ(20U, signature.size());
981
982    EXPECT_EQ(0, GetParam()->keymaster0_calls());
983}
984
985TEST_P(SigningOperationsTest, HmacRfc4231TestCase1) {
986    uint8_t key_data[] = {
987        0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
988        0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
989    };
990    string message = "Hi There";
991    uint8_t sha_224_expected[] = {
992        0x89, 0x6f, 0xb1, 0x12, 0x8a, 0xbb, 0xdf, 0x19, 0x68, 0x32, 0x10, 0x7c, 0xd4, 0x9d,
993        0xf3, 0x3f, 0x47, 0xb4, 0xb1, 0x16, 0x99, 0x12, 0xba, 0x4f, 0x53, 0x68, 0x4b, 0x22,
994    };
995    uint8_t sha_256_expected[] = {
996        0xb0, 0x34, 0x4c, 0x61, 0xd8, 0xdb, 0x38, 0x53, 0x5c, 0xa8, 0xaf,
997        0xce, 0xaf, 0x0b, 0xf1, 0x2b, 0x88, 0x1d, 0xc2, 0x00, 0xc9, 0x83,
998        0x3d, 0xa7, 0x26, 0xe9, 0x37, 0x6c, 0x2e, 0x32, 0xcf, 0xf7,
999    };
1000    uint8_t sha_384_expected[] = {
1001        0xaf, 0xd0, 0x39, 0x44, 0xd8, 0x48, 0x95, 0x62, 0x6b, 0x08, 0x25, 0xf4,
1002        0xab, 0x46, 0x90, 0x7f, 0x15, 0xf9, 0xda, 0xdb, 0xe4, 0x10, 0x1e, 0xc6,
1003        0x82, 0xaa, 0x03, 0x4c, 0x7c, 0xeb, 0xc5, 0x9c, 0xfa, 0xea, 0x9e, 0xa9,
1004        0x07, 0x6e, 0xde, 0x7f, 0x4a, 0xf1, 0x52, 0xe8, 0xb2, 0xfa, 0x9c, 0xb6,
1005    };
1006    uint8_t sha_512_expected[] = {
1007        0x87, 0xaa, 0x7c, 0xde, 0xa5, 0xef, 0x61, 0x9d, 0x4f, 0xf0, 0xb4, 0x24, 0x1a,
1008        0x1d, 0x6c, 0xb0, 0x23, 0x79, 0xf4, 0xe2, 0xce, 0x4e, 0xc2, 0x78, 0x7a, 0xd0,
1009        0xb3, 0x05, 0x45, 0xe1, 0x7c, 0xde, 0xda, 0xa8, 0x33, 0xb7, 0xd6, 0xb8, 0xa7,
1010        0x02, 0x03, 0x8b, 0x27, 0x4e, 0xae, 0xa3, 0xf4, 0xe4, 0xbe, 0x9d, 0x91, 0x4e,
1011        0xeb, 0x61, 0xf1, 0x70, 0x2e, 0x69, 0x6c, 0x20, 0x3a, 0x12, 0x68, 0x54,
1012    };
1013
1014    string key = make_string(key_data);
1015
1016    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
1017    if (!GetParam()->minimal_digest_set()) {
1018        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
1019        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
1020        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
1021    }
1022
1023    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1024}
1025
1026TEST_P(SigningOperationsTest, HmacRfc4231TestCase2) {
1027    string key = "Jefe";
1028    string message = "what do ya want for nothing?";
1029    uint8_t sha_224_expected[] = {
1030        0xa3, 0x0e, 0x01, 0x09, 0x8b, 0xc6, 0xdb, 0xbf, 0x45, 0x69, 0x0f, 0x3a, 0x7e, 0x9e,
1031        0x6d, 0x0f, 0x8b, 0xbe, 0xa2, 0xa3, 0x9e, 0x61, 0x48, 0x00, 0x8f, 0xd0, 0x5e, 0x44,
1032    };
1033    uint8_t sha_256_expected[] = {
1034        0x5b, 0xdc, 0xc1, 0x46, 0xbf, 0x60, 0x75, 0x4e, 0x6a, 0x04, 0x24,
1035        0x26, 0x08, 0x95, 0x75, 0xc7, 0x5a, 0x00, 0x3f, 0x08, 0x9d, 0x27,
1036        0x39, 0x83, 0x9d, 0xec, 0x58, 0xb9, 0x64, 0xec, 0x38, 0x43,
1037    };
1038    uint8_t sha_384_expected[] = {
1039        0xaf, 0x45, 0xd2, 0xe3, 0x76, 0x48, 0x40, 0x31, 0x61, 0x7f, 0x78, 0xd2,
1040        0xb5, 0x8a, 0x6b, 0x1b, 0x9c, 0x7e, 0xf4, 0x64, 0xf5, 0xa0, 0x1b, 0x47,
1041        0xe4, 0x2e, 0xc3, 0x73, 0x63, 0x22, 0x44, 0x5e, 0x8e, 0x22, 0x40, 0xca,
1042        0x5e, 0x69, 0xe2, 0xc7, 0x8b, 0x32, 0x39, 0xec, 0xfa, 0xb2, 0x16, 0x49,
1043    };
1044    uint8_t sha_512_expected[] = {
1045        0x16, 0x4b, 0x7a, 0x7b, 0xfc, 0xf8, 0x19, 0xe2, 0xe3, 0x95, 0xfb, 0xe7, 0x3b,
1046        0x56, 0xe0, 0xa3, 0x87, 0xbd, 0x64, 0x22, 0x2e, 0x83, 0x1f, 0xd6, 0x10, 0x27,
1047        0x0c, 0xd7, 0xea, 0x25, 0x05, 0x54, 0x97, 0x58, 0xbf, 0x75, 0xc0, 0x5a, 0x99,
1048        0x4a, 0x6d, 0x03, 0x4f, 0x65, 0xf8, 0xf0, 0xe6, 0xfd, 0xca, 0xea, 0xb1, 0xa3,
1049        0x4d, 0x4a, 0x6b, 0x4b, 0x63, 0x6e, 0x07, 0x0a, 0x38, 0xbc, 0xe7, 0x37,
1050    };
1051
1052    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
1053    if (!GetParam()->minimal_digest_set()) {
1054        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
1055        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
1056        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
1057        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
1058    }
1059
1060    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1061}
1062
1063TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
1064    string key(20, 0xaa);
1065    string message(50, 0xdd);
1066    uint8_t sha_224_expected[] = {
1067        0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
1068        0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
1069    };
1070    uint8_t sha_256_expected[] = {
1071        0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
1072        0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
1073        0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
1074    };
1075    uint8_t sha_384_expected[] = {
1076        0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
1077        0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
1078        0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
1079        0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
1080    };
1081    uint8_t sha_512_expected[] = {
1082        0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
1083        0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
1084        0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
1085        0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
1086        0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
1087    };
1088
1089    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
1090    if (!GetParam()->minimal_digest_set()) {
1091        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
1092        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
1093        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
1094        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
1095    }
1096
1097    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1098}
1099
1100TEST_P(SigningOperationsTest, HmacRfc4231TestCase4) {
1101    uint8_t key_data[25] = {
1102        0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
1103        0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,
1104    };
1105    string key = make_string(key_data);
1106    string message(50, 0xcd);
1107    uint8_t sha_224_expected[] = {
1108        0x6c, 0x11, 0x50, 0x68, 0x74, 0x01, 0x3c, 0xac, 0x6a, 0x2a, 0xbc, 0x1b, 0xb3, 0x82,
1109        0x62, 0x7c, 0xec, 0x6a, 0x90, 0xd8, 0x6e, 0xfc, 0x01, 0x2d, 0xe7, 0xaf, 0xec, 0x5a,
1110    };
1111    uint8_t sha_256_expected[] = {
1112        0x82, 0x55, 0x8a, 0x38, 0x9a, 0x44, 0x3c, 0x0e, 0xa4, 0xcc, 0x81,
1113        0x98, 0x99, 0xf2, 0x08, 0x3a, 0x85, 0xf0, 0xfa, 0xa3, 0xe5, 0x78,
1114        0xf8, 0x07, 0x7a, 0x2e, 0x3f, 0xf4, 0x67, 0x29, 0x66, 0x5b,
1115    };
1116    uint8_t sha_384_expected[] = {
1117        0x3e, 0x8a, 0x69, 0xb7, 0x78, 0x3c, 0x25, 0x85, 0x19, 0x33, 0xab, 0x62,
1118        0x90, 0xaf, 0x6c, 0xa7, 0x7a, 0x99, 0x81, 0x48, 0x08, 0x50, 0x00, 0x9c,
1119        0xc5, 0x57, 0x7c, 0x6e, 0x1f, 0x57, 0x3b, 0x4e, 0x68, 0x01, 0xdd, 0x23,
1120        0xc4, 0xa7, 0xd6, 0x79, 0xcc, 0xf8, 0xa3, 0x86, 0xc6, 0x74, 0xcf, 0xfb,
1121    };
1122    uint8_t sha_512_expected[] = {
1123        0xb0, 0xba, 0x46, 0x56, 0x37, 0x45, 0x8c, 0x69, 0x90, 0xe5, 0xa8, 0xc5, 0xf6,
1124        0x1d, 0x4a, 0xf7, 0xe5, 0x76, 0xd9, 0x7f, 0xf9, 0x4b, 0x87, 0x2d, 0xe7, 0x6f,
1125        0x80, 0x50, 0x36, 0x1e, 0xe3, 0xdb, 0xa9, 0x1c, 0xa5, 0xc1, 0x1a, 0xa2, 0x5e,
1126        0xb4, 0xd6, 0x79, 0x27, 0x5c, 0xc5, 0x78, 0x80, 0x63, 0xa5, 0xf1, 0x97, 0x41,
1127        0x12, 0x0c, 0x4f, 0x2d, 0xe2, 0xad, 0xeb, 0xeb, 0x10, 0xa2, 0x98, 0xdd,
1128    };
1129
1130    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
1131    if (!GetParam()->minimal_digest_set()) {
1132        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
1133        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
1134        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
1135        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
1136    }
1137
1138    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1139}
1140
1141TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
1142    string key(20, 0x0c);
1143    string message = "Test With Truncation";
1144
1145    uint8_t sha_224_expected[] = {
1146        0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
1147        0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
1148    };
1149    uint8_t sha_256_expected[] = {
1150        0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
1151        0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
1152    };
1153    uint8_t sha_384_expected[] = {
1154        0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
1155        0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
1156    };
1157    uint8_t sha_512_expected[] = {
1158        0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
1159        0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
1160    };
1161
1162    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
1163    if (!GetParam()->minimal_digest_set()) {
1164        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
1165        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
1166        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
1167    }
1168
1169    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1170}
1171
1172TEST_P(SigningOperationsTest, HmacRfc4231TestCase6) {
1173    string key(131, 0xaa);
1174    string message = "Test Using Larger Than Block-Size Key - Hash Key First";
1175
1176    uint8_t sha_224_expected[] = {
1177        0x95, 0xe9, 0xa0, 0xdb, 0x96, 0x20, 0x95, 0xad, 0xae, 0xbe, 0x9b, 0x2d, 0x6f, 0x0d,
1178        0xbc, 0xe2, 0xd4, 0x99, 0xf1, 0x12, 0xf2, 0xd2, 0xb7, 0x27, 0x3f, 0xa6, 0x87, 0x0e,
1179    };
1180    uint8_t sha_256_expected[] = {
1181        0x60, 0xe4, 0x31, 0x59, 0x1e, 0xe0, 0xb6, 0x7f, 0x0d, 0x8a, 0x26,
1182        0xaa, 0xcb, 0xf5, 0xb7, 0x7f, 0x8e, 0x0b, 0xc6, 0x21, 0x37, 0x28,
1183        0xc5, 0x14, 0x05, 0x46, 0x04, 0x0f, 0x0e, 0xe3, 0x7f, 0x54,
1184    };
1185    uint8_t sha_384_expected[] = {
1186        0x4e, 0xce, 0x08, 0x44, 0x85, 0x81, 0x3e, 0x90, 0x88, 0xd2, 0xc6, 0x3a,
1187        0x04, 0x1b, 0xc5, 0xb4, 0x4f, 0x9e, 0xf1, 0x01, 0x2a, 0x2b, 0x58, 0x8f,
1188        0x3c, 0xd1, 0x1f, 0x05, 0x03, 0x3a, 0xc4, 0xc6, 0x0c, 0x2e, 0xf6, 0xab,
1189        0x40, 0x30, 0xfe, 0x82, 0x96, 0x24, 0x8d, 0xf1, 0x63, 0xf4, 0x49, 0x52,
1190    };
1191    uint8_t sha_512_expected[] = {
1192        0x80, 0xb2, 0x42, 0x63, 0xc7, 0xc1, 0xa3, 0xeb, 0xb7, 0x14, 0x93, 0xc1, 0xdd,
1193        0x7b, 0xe8, 0xb4, 0x9b, 0x46, 0xd1, 0xf4, 0x1b, 0x4a, 0xee, 0xc1, 0x12, 0x1b,
1194        0x01, 0x37, 0x83, 0xf8, 0xf3, 0x52, 0x6b, 0x56, 0xd0, 0x37, 0xe0, 0x5f, 0x25,
1195        0x98, 0xbd, 0x0f, 0xd2, 0x21, 0x5d, 0x6a, 0x1e, 0x52, 0x95, 0xe6, 0x4f, 0x73,
1196        0xf6, 0x3f, 0x0a, 0xec, 0x8b, 0x91, 0x5a, 0x98, 0x5d, 0x78, 0x65, 0x98,
1197    };
1198
1199    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
1200    if (!GetParam()->minimal_digest_set()) {
1201        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
1202        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
1203        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
1204    }
1205
1206    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1207}
1208
1209TEST_P(SigningOperationsTest, HmacRfc4231TestCase7) {
1210    string key(131, 0xaa);
1211    string message = "This is a test using a larger than block-size key and a larger than "
1212                     "block-size data. The key needs to be hashed before being used by the HMAC "
1213                     "algorithm.";
1214
1215    uint8_t sha_224_expected[] = {
1216        0x3a, 0x85, 0x41, 0x66, 0xac, 0x5d, 0x9f, 0x02, 0x3f, 0x54, 0xd5, 0x17, 0xd0, 0xb3,
1217        0x9d, 0xbd, 0x94, 0x67, 0x70, 0xdb, 0x9c, 0x2b, 0x95, 0xc9, 0xf6, 0xf5, 0x65, 0xd1,
1218    };
1219    uint8_t sha_256_expected[] = {
1220        0x9b, 0x09, 0xff, 0xa7, 0x1b, 0x94, 0x2f, 0xcb, 0x27, 0x63, 0x5f,
1221        0xbc, 0xd5, 0xb0, 0xe9, 0x44, 0xbf, 0xdc, 0x63, 0x64, 0x4f, 0x07,
1222        0x13, 0x93, 0x8a, 0x7f, 0x51, 0x53, 0x5c, 0x3a, 0x35, 0xe2,
1223    };
1224    uint8_t sha_384_expected[] = {
1225        0x66, 0x17, 0x17, 0x8e, 0x94, 0x1f, 0x02, 0x0d, 0x35, 0x1e, 0x2f, 0x25,
1226        0x4e, 0x8f, 0xd3, 0x2c, 0x60, 0x24, 0x20, 0xfe, 0xb0, 0xb8, 0xfb, 0x9a,
1227        0xdc, 0xce, 0xbb, 0x82, 0x46, 0x1e, 0x99, 0xc5, 0xa6, 0x78, 0xcc, 0x31,
1228        0xe7, 0x99, 0x17, 0x6d, 0x38, 0x60, 0xe6, 0x11, 0x0c, 0x46, 0x52, 0x3e,
1229    };
1230    uint8_t sha_512_expected[] = {
1231        0xe3, 0x7b, 0x6a, 0x77, 0x5d, 0xc8, 0x7d, 0xba, 0xa4, 0xdf, 0xa9, 0xf9, 0x6e,
1232        0x5e, 0x3f, 0xfd, 0xde, 0xbd, 0x71, 0xf8, 0x86, 0x72, 0x89, 0x86, 0x5d, 0xf5,
1233        0xa3, 0x2d, 0x20, 0xcd, 0xc9, 0x44, 0xb6, 0x02, 0x2c, 0xac, 0x3c, 0x49, 0x82,
1234        0xb1, 0x0d, 0x5e, 0xeb, 0x55, 0xc3, 0xe4, 0xde, 0x15, 0x13, 0x46, 0x76, 0xfb,
1235        0x6d, 0xe0, 0x44, 0x60, 0x65, 0xc9, 0x74, 0x40, 0xfa, 0x8c, 0x6a, 0x58,
1236    };
1237
1238    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
1239    if (!GetParam()->minimal_digest_set()) {
1240        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
1241        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
1242        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
1243    }
1244
1245    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1246}
1247
1248TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
1249    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1250                                           .HmacKey(128)
1251                                           .Digest(KM_DIGEST_SHA_2_256)
1252                                           .Authorization(TAG_MIN_MAC_LENGTH, 256)));
1253    AuthorizationSet begin_params(client_params());
1254    begin_params.push_back(TAG_MAC_LENGTH, 264);
1255    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1256    ASSERT_EQ(KM_ERROR_UNSUPPORTED_MAC_LENGTH,
1257              BeginOperation(KM_PURPOSE_SIGN, begin_params, nullptr /* output_params */));
1258
1259    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1260}
1261
1262TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
1263    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1264                                           .HmacKey(128)
1265                                           .Digest(KM_DIGEST_SHA_2_256)
1266                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1267    AuthorizationSet begin_params(client_params());
1268    begin_params.push_back(TAG_MAC_LENGTH, 120);
1269    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1270    ASSERT_EQ(KM_ERROR_INVALID_MAC_LENGTH,
1271              BeginOperation(KM_PURPOSE_SIGN, begin_params, nullptr /* output_params */));
1272
1273    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1274}
1275
1276// TODO(swillden): Add more verification failure tests.
1277
1278typedef Keymaster1Test VerificationOperationsTest;
1279INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, VerificationOperationsTest, test_params);
1280
1281TEST_P(VerificationOperationsTest, RsaSuccess) {
1282    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1283                                           .RsaSigningKey(256, 3)
1284                                           .Digest(KM_DIGEST_NONE)
1285                                           .Padding(KM_PAD_NONE)));
1286    string message = "12345678901234567890123456789012";
1287    string signature;
1288    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
1289    VerifyMessage(message, signature, KM_DIGEST_NONE, KM_PAD_NONE);
1290
1291    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1292        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1293}
1294
1295TEST_P(VerificationOperationsTest, RsaPssSha256Success) {
1296    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1297                                           .RsaSigningKey(512, 3)
1298                                           .Digest(KM_DIGEST_SHA_2_256)
1299                                           .Padding(KM_PAD_RSA_PSS)));
1300    // Use large message, which won't work without digesting.
1301    string message(1024, 'a');
1302    string signature;
1303    SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
1304    VerifyMessage(message, signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
1305
1306    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1307        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1308}
1309
1310TEST_P(VerificationOperationsTest, RsaPssSha224Success) {
1311    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1312                                           .RsaSigningKey(512, 3)
1313                                           .Digest(KM_DIGEST_SHA_2_224)
1314                                           .Padding(KM_PAD_RSA_PSS)));
1315    // Use large message, which won't work without digesting.
1316    string message(1024, 'a');
1317    string signature;
1318    SignMessage(message, &signature, KM_DIGEST_SHA_2_224, KM_PAD_RSA_PSS);
1319    VerifyMessage(message, signature, KM_DIGEST_SHA_2_224, KM_PAD_RSA_PSS);
1320
1321    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1322        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1323
1324    // Verify with OpenSSL.
1325    string pubkey;
1326    EXPECT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &pubkey));
1327
1328    const uint8_t* p = reinterpret_cast<const uint8_t*>(pubkey.data());
1329    unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(
1330        d2i_PUBKEY(nullptr /* alloc new */, &p, pubkey.size()));
1331    ASSERT_TRUE(pkey.get());
1332
1333    EVP_MD_CTX digest_ctx;
1334    EVP_MD_CTX_init(&digest_ctx);
1335    EVP_PKEY_CTX* pkey_ctx;
1336    EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, EVP_sha224(), nullptr /* engine */,
1337                                      pkey.get()));
1338    EXPECT_EQ(1, EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING));
1339    EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(), message.size()));
1340    EXPECT_EQ(1,
1341              EVP_DigestVerifyFinal(&digest_ctx, reinterpret_cast<const uint8_t*>(signature.data()),
1342                                    signature.size()));
1343    EVP_MD_CTX_cleanup(&digest_ctx);
1344}
1345
1346TEST_P(VerificationOperationsTest, RsaPssSha256CorruptSignature) {
1347    GenerateKey(AuthorizationSetBuilder()
1348                    .RsaSigningKey(512, 3)
1349                    .Digest(KM_DIGEST_SHA_2_256)
1350                    .Padding(KM_PAD_RSA_PSS));
1351    string message(1024, 'a');
1352    string signature;
1353    SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
1354    ++signature[signature.size() / 2];
1355
1356    AuthorizationSet begin_params(client_params());
1357    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1358    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PSS);
1359    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1360
1361    string result;
1362    size_t input_consumed;
1363    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
1364    EXPECT_EQ(message.size(), input_consumed);
1365    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(signature, &result));
1366
1367    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1368        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1369}
1370
1371TEST_P(VerificationOperationsTest, RsaPssSha256CorruptInput) {
1372    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1373                                           .RsaSigningKey(512, 3)
1374                                           .Digest(KM_DIGEST_SHA_2_256)
1375                                           .Padding(KM_PAD_RSA_PSS)));
1376    // Use large message, which won't work without digesting.
1377    string message(1024, 'a');
1378    string signature;
1379    SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
1380    ++message[message.size() / 2];
1381
1382    AuthorizationSet begin_params(client_params());
1383    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1384    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PSS);
1385    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1386
1387    string result;
1388    size_t input_consumed;
1389    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
1390    EXPECT_EQ(message.size(), input_consumed);
1391    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(signature, &result));
1392
1393    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1394        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1395}
1396
1397TEST_P(VerificationOperationsTest, RsaPkcs1Sha256Success) {
1398    GenerateKey(AuthorizationSetBuilder()
1399                    .RsaSigningKey(512, 3)
1400                    .Digest(KM_DIGEST_SHA_2_256)
1401                    .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN));
1402    string message(1024, 'a');
1403    string signature;
1404    SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
1405    VerifyMessage(message, signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
1406
1407    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1408        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1409}
1410
1411TEST_P(VerificationOperationsTest, RsaPks1Sha224Success) {
1412    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1413                                           .RsaSigningKey(512, 3)
1414                                           .Digest(KM_DIGEST_SHA_2_224)
1415                                           .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
1416    // Use large message, which won't work without digesting.
1417    string message(1024, 'a');
1418    string signature;
1419    SignMessage(message, &signature, KM_DIGEST_SHA_2_224, KM_PAD_RSA_PKCS1_1_5_SIGN);
1420    VerifyMessage(message, signature, KM_DIGEST_SHA_2_224, KM_PAD_RSA_PKCS1_1_5_SIGN);
1421
1422    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1423        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1424
1425    // Verify with OpenSSL.
1426    string pubkey;
1427    EXPECT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &pubkey));
1428
1429    const uint8_t* p = reinterpret_cast<const uint8_t*>(pubkey.data());
1430    unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(
1431        d2i_PUBKEY(nullptr /* alloc new */, &p, pubkey.size()));
1432    ASSERT_TRUE(pkey.get());
1433
1434    EVP_MD_CTX digest_ctx;
1435    EVP_MD_CTX_init(&digest_ctx);
1436    EVP_PKEY_CTX* pkey_ctx;
1437    EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, EVP_sha224(), nullptr /* engine */,
1438                                      pkey.get()));
1439    EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(), message.size()));
1440    EXPECT_EQ(1,
1441              EVP_DigestVerifyFinal(&digest_ctx, reinterpret_cast<const uint8_t*>(signature.data()),
1442                                    signature.size()));
1443    EVP_MD_CTX_cleanup(&digest_ctx);
1444}
1445
1446TEST_P(VerificationOperationsTest, RsaPkcs1Sha256CorruptSignature) {
1447    GenerateKey(AuthorizationSetBuilder()
1448                    .RsaSigningKey(512, 3)
1449                    .Digest(KM_DIGEST_SHA_2_256)
1450                    .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN));
1451    string message(1024, 'a');
1452    string signature;
1453    SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
1454    ++signature[signature.size() / 2];
1455
1456    AuthorizationSet begin_params(client_params());
1457    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1458    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
1459    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1460
1461    string result;
1462    size_t input_consumed;
1463    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
1464    EXPECT_EQ(message.size(), input_consumed);
1465    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(signature, &result));
1466
1467    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1468        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1469}
1470
1471TEST_P(VerificationOperationsTest, RsaPkcs1Sha256CorruptInput) {
1472    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1473                                           .RsaSigningKey(512, 3)
1474                                           .Digest(KM_DIGEST_SHA_2_256)
1475                                           .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
1476    // Use large message, which won't work without digesting.
1477    string message(1024, 'a');
1478    string signature;
1479    SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
1480    ++message[message.size() / 2];
1481
1482    AuthorizationSet begin_params(client_params());
1483    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1484    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
1485    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1486
1487    string result;
1488    size_t input_consumed;
1489    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
1490    EXPECT_EQ(message.size(), input_consumed);
1491    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(signature, &result));
1492
1493    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1494        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1495}
1496
1497TEST_P(VerificationOperationsTest, RsaAllDigestAndPadCombinations) {
1498    vector<keymaster_digest_t> digests = {
1499        KM_DIGEST_NONE,      KM_DIGEST_MD5,       KM_DIGEST_SHA1,      KM_DIGEST_SHA_2_224,
1500        KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512,
1501    };
1502
1503    vector<keymaster_padding_t> padding_modes{
1504        KM_PAD_NONE, KM_PAD_RSA_PKCS1_1_5_SIGN, KM_PAD_RSA_PSS,
1505    };
1506
1507    int trial_count = 0;
1508    for (keymaster_padding_t padding_mode : padding_modes) {
1509        for (keymaster_digest_t digest : digests) {
1510            if (digest != KM_DIGEST_NONE && padding_mode == KM_PAD_NONE)
1511                // Digesting requires padding
1512                continue;
1513
1514            // Compute key & message size that will work.
1515            size_t key_bits = 0;
1516            size_t message_len = 1000;
1517
1518            if (digest == KM_DIGEST_NONE) {
1519                key_bits = 256;
1520                switch (padding_mode) {
1521                case KM_PAD_NONE:
1522                    // Match key size.
1523                    message_len = key_bits / 8;
1524                    break;
1525                case KM_PAD_RSA_PKCS1_1_5_SIGN:
1526                    message_len = key_bits / 8 - 11;
1527                    break;
1528                case KM_PAD_RSA_PSS:
1529                    // PSS requires a digest.
1530                    continue;
1531                default:
1532                    FAIL() << "Missing padding";
1533                    break;
1534                }
1535            } else {
1536                size_t digest_bits;
1537                switch (digest) {
1538                case KM_DIGEST_MD5:
1539                    digest_bits = 128;
1540                    break;
1541                case KM_DIGEST_SHA1:
1542                    digest_bits = 160;
1543                    break;
1544                case KM_DIGEST_SHA_2_224:
1545                    digest_bits = 224;
1546                    break;
1547                case KM_DIGEST_SHA_2_256:
1548                    digest_bits = 256;
1549                    break;
1550                case KM_DIGEST_SHA_2_384:
1551                    digest_bits = 384;
1552                    break;
1553                case KM_DIGEST_SHA_2_512:
1554                    digest_bits = 512;
1555                    break;
1556                default:
1557                    FAIL() << "Missing digest";
1558                }
1559
1560                switch (padding_mode) {
1561                case KM_PAD_RSA_PKCS1_1_5_SIGN:
1562                    key_bits = digest_bits + 8 * (11 + 19);
1563                    break;
1564                case KM_PAD_RSA_PSS:
1565                    key_bits = digest_bits + 22 * 8;
1566                    break;
1567                default:
1568                    FAIL() << "Missing padding";
1569                    break;
1570                }
1571            }
1572
1573            GenerateKey(AuthorizationSetBuilder()
1574                            .RsaSigningKey(key_bits, 3)
1575                            .Digest(digest)
1576                            .Padding(padding_mode));
1577            string message(message_len, 'a');
1578            string signature;
1579            SignMessage(message, &signature, digest, padding_mode);
1580            VerifyMessage(message, signature, digest, padding_mode);
1581            ++trial_count;
1582        }
1583    }
1584
1585    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1586        EXPECT_EQ(trial_count * 4, GetParam()->keymaster0_calls());
1587}
1588
1589TEST_P(VerificationOperationsTest, EcdsaSuccess) {
1590    ASSERT_EQ(KM_ERROR_OK,
1591              GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(KM_DIGEST_NONE)));
1592    string message = "12345678901234567890123456789012";
1593    string signature;
1594    SignMessage(message, &signature, KM_DIGEST_NONE);
1595    VerifyMessage(message, signature, KM_DIGEST_NONE);
1596
1597    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1598        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1599}
1600
1601TEST_P(VerificationOperationsTest, EcdsaTooShort) {
1602    ASSERT_EQ(KM_ERROR_OK,
1603              GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(KM_DIGEST_NONE)));
1604    string message = "12345678901234567890";
1605    string signature;
1606    SignMessage(message, &signature, KM_DIGEST_NONE);
1607    VerifyMessage(message, signature, KM_DIGEST_NONE);
1608
1609    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1610        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1611}
1612
1613TEST_P(VerificationOperationsTest, EcdsaSlightlyTooLong) {
1614    ASSERT_EQ(KM_ERROR_OK,
1615              GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(521).Digest(KM_DIGEST_NONE)));
1616
1617    string message(66, 'a');
1618    string signature;
1619    SignMessage(message, &signature, KM_DIGEST_NONE);
1620    VerifyMessage(message, signature, KM_DIGEST_NONE);
1621
1622    // Modifying low-order bits doesn't matter, because they didn't get signed.  Ugh.
1623    message[65] ^= 7;
1624    VerifyMessage(message, signature, KM_DIGEST_NONE);
1625
1626    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1627        EXPECT_EQ(5, GetParam()->keymaster0_calls());
1628}
1629
1630TEST_P(VerificationOperationsTest, EcdsaSha256Success) {
1631    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1632                                           .EcdsaSigningKey(256)
1633                                           .Digest(KM_DIGEST_SHA_2_256)
1634                                           .Digest(KM_DIGEST_NONE)));
1635    string message = "12345678901234567890123456789012";
1636    string signature;
1637    SignMessage(message, &signature, KM_DIGEST_SHA_2_256);
1638    VerifyMessage(message, signature, KM_DIGEST_SHA_2_256);
1639
1640    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1641        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1642
1643    // Just for giggles, try verifying with the wrong digest.
1644    AuthorizationSet begin_params(client_params());
1645    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
1646    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1647
1648    string result;
1649    size_t input_consumed;
1650    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
1651    EXPECT_EQ(message.size(), input_consumed);
1652    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(signature, &result));
1653}
1654
1655TEST_P(VerificationOperationsTest, EcdsaSha224Success) {
1656    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(
1657                               KM_DIGEST_SHA_2_224)));
1658
1659    string message = "12345678901234567890123456789012";
1660    string signature;
1661    SignMessage(message, &signature, KM_DIGEST_SHA_2_224);
1662    VerifyMessage(message, signature, KM_DIGEST_SHA_2_224);
1663
1664    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1665        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1666
1667    // Just for giggles, try verifying with the wrong digest.
1668    AuthorizationSet begin_params(client_params());
1669    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
1670    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1671
1672    string result;
1673    size_t input_consumed;
1674    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
1675    EXPECT_EQ(message.size(), input_consumed);
1676    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(signature, &result));
1677}
1678
1679TEST_P(VerificationOperationsTest, EcdsaAllDigestsAndKeySizes) {
1680    keymaster_digest_t digests[] = {
1681        KM_DIGEST_SHA1,      KM_DIGEST_SHA_2_224, KM_DIGEST_SHA_2_256,
1682        KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512,
1683    };
1684    size_t key_sizes[] = {224, 256, 384, 521};
1685
1686    string message = "1234567890";
1687    string signature;
1688
1689    for (auto key_size : key_sizes) {
1690        AuthorizationSetBuilder builder;
1691        builder.EcdsaSigningKey(key_size);
1692        for (auto digest : digests)
1693            builder.Digest(digest);
1694        ASSERT_EQ(KM_ERROR_OK, GenerateKey(builder));
1695
1696        for (auto digest : digests) {
1697            SignMessage(message, &signature, digest);
1698            VerifyMessage(message, signature, digest);
1699        }
1700    }
1701
1702    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1703        EXPECT_EQ(static_cast<int>(array_length(key_sizes) * (1 + 3 * array_length(digests))),
1704                  GetParam()->keymaster0_calls());
1705}
1706
1707TEST_P(VerificationOperationsTest, HmacSha1Success) {
1708    if (GetParam()->minimal_digest_set())
1709        // Can't emulate missing digests for HMAC.
1710        return;
1711
1712    GenerateKey(AuthorizationSetBuilder()
1713                    .HmacKey(128)
1714                    .Digest(KM_DIGEST_SHA1)
1715                    .Authorization(TAG_MIN_MAC_LENGTH, 128));
1716    string message = "123456789012345678901234567890123456789012345678";
1717    string signature;
1718    MacMessage(message, &signature, 160);
1719    VerifyMac(message, signature);
1720
1721    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1722}
1723
1724TEST_P(VerificationOperationsTest, HmacSha224Success) {
1725    if (GetParam()->minimal_digest_set())
1726        // Can't emulate missing digests for HMAC.
1727        return;
1728
1729    GenerateKey(AuthorizationSetBuilder()
1730                    .HmacKey(128)
1731                    .Digest(KM_DIGEST_SHA_2_224)
1732                    .Authorization(TAG_MIN_MAC_LENGTH, 128));
1733    string message = "123456789012345678901234567890123456789012345678";
1734    string signature;
1735    MacMessage(message, &signature, 224);
1736    VerifyMac(message, signature);
1737
1738    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1739}
1740
1741TEST_P(VerificationOperationsTest, HmacSha256Success) {
1742    GenerateKey(AuthorizationSetBuilder()
1743                    .HmacKey(128)
1744                    .Digest(KM_DIGEST_SHA_2_256)
1745                    .Authorization(TAG_MIN_MAC_LENGTH, 128));
1746    string message = "123456789012345678901234567890123456789012345678";
1747    string signature;
1748    MacMessage(message, &signature, 256);
1749    VerifyMac(message, signature);
1750
1751    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1752}
1753
1754TEST_P(VerificationOperationsTest, HmacSha256TooShortMac) {
1755    GenerateKey(AuthorizationSetBuilder()
1756                    .HmacKey(128)
1757                    .Digest(KM_DIGEST_SHA_2_256)
1758                    .Authorization(TAG_MIN_MAC_LENGTH, 128));
1759    string message = "123456789012345678901234567890123456789012345678";
1760    string signature;
1761    MacMessage(message, &signature, 256);
1762
1763    // Shorten to 128 bits, should still work.
1764    signature.resize(128 / 8);
1765    VerifyMac(message, signature);
1766
1767    // Drop one more byte.
1768    signature.resize(signature.length() - 1);
1769
1770    AuthorizationSet begin_params(client_params());
1771    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1772    string result;
1773    size_t input_consumed;
1774    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
1775    EXPECT_EQ(KM_ERROR_INVALID_MAC_LENGTH, FinishOperation(signature, &result));
1776
1777    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1778}
1779
1780TEST_P(VerificationOperationsTest, HmacSha384Success) {
1781    if (GetParam()->minimal_digest_set())
1782        // Can't emulate missing digests for HMAC.
1783        return;
1784
1785    GenerateKey(AuthorizationSetBuilder()
1786                    .HmacKey(128)
1787                    .Digest(KM_DIGEST_SHA_2_384)
1788                    .Authorization(TAG_MIN_MAC_LENGTH, 128));
1789    string message = "123456789012345678901234567890123456789012345678";
1790    string signature;
1791    MacMessage(message, &signature, 384);
1792    VerifyMac(message, signature);
1793
1794    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1795}
1796
1797TEST_P(VerificationOperationsTest, HmacSha512Success) {
1798    if (GetParam()->minimal_digest_set())
1799        // Can't emulate missing digests for HMAC.
1800        return;
1801
1802    GenerateKey(AuthorizationSetBuilder()
1803                    .HmacKey(128)
1804                    .Digest(KM_DIGEST_SHA_2_512)
1805                    .Authorization(TAG_MIN_MAC_LENGTH, 128));
1806    string message = "123456789012345678901234567890123456789012345678";
1807    string signature;
1808    MacMessage(message, &signature, 512);
1809    VerifyMac(message, signature);
1810
1811    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1812}
1813
1814typedef Keymaster1Test ExportKeyTest;
1815INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, ExportKeyTest, test_params);
1816
1817TEST_P(ExportKeyTest, RsaSuccess) {
1818    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1819                                           .RsaSigningKey(256, 3)
1820                                           .Digest(KM_DIGEST_NONE)
1821                                           .Padding(KM_PAD_NONE)));
1822    string export_data;
1823    ASSERT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &export_data));
1824    EXPECT_GT(export_data.length(), 0U);
1825
1826    // TODO(swillden): Verify that the exported key is actually usable to verify signatures.
1827
1828    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1829        EXPECT_EQ(2, GetParam()->keymaster0_calls());
1830}
1831
1832TEST_P(ExportKeyTest, EcdsaSuccess) {
1833    ASSERT_EQ(KM_ERROR_OK,
1834              GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
1835    string export_data;
1836    ASSERT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &export_data));
1837    EXPECT_GT(export_data.length(), 0U);
1838
1839    // TODO(swillden): Verify that the exported key is actually usable to verify signatures.
1840
1841    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1842        EXPECT_EQ(2, GetParam()->keymaster0_calls());
1843}
1844
1845TEST_P(ExportKeyTest, RsaUnsupportedKeyFormat) {
1846    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1847                                           .RsaSigningKey(256, 3)
1848                                           .Digest(KM_DIGEST_NONE)
1849                                           .Padding(KM_PAD_NONE)));
1850    string export_data;
1851    ASSERT_EQ(KM_ERROR_UNSUPPORTED_KEY_FORMAT, ExportKey(KM_KEY_FORMAT_PKCS8, &export_data));
1852
1853    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1854        EXPECT_EQ(2, GetParam()->keymaster0_calls());
1855}
1856
1857TEST_P(ExportKeyTest, RsaCorruptedKeyBlob) {
1858    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1859                                           .RsaSigningKey(256, 3)
1860                                           .Digest(KM_DIGEST_NONE)
1861                                           .Padding(KM_PAD_NONE)));
1862    corrupt_key_blob();
1863    string export_data;
1864    ASSERT_EQ(KM_ERROR_INVALID_KEY_BLOB, ExportKey(KM_KEY_FORMAT_X509, &export_data));
1865
1866    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1867        EXPECT_EQ(2, GetParam()->keymaster0_calls());
1868}
1869
1870TEST_P(ExportKeyTest, AesKeyExportFails) {
1871    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().AesEncryptionKey(128)));
1872    string export_data;
1873
1874    EXPECT_EQ(KM_ERROR_UNSUPPORTED_KEY_FORMAT, ExportKey(KM_KEY_FORMAT_X509, &export_data));
1875    EXPECT_EQ(KM_ERROR_UNSUPPORTED_KEY_FORMAT, ExportKey(KM_KEY_FORMAT_PKCS8, &export_data));
1876    EXPECT_EQ(KM_ERROR_UNSUPPORTED_KEY_FORMAT, ExportKey(KM_KEY_FORMAT_RAW, &export_data));
1877
1878    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1879}
1880
1881static string read_file(const string& file_name) {
1882    ifstream file_stream(file_name, std::ios::binary);
1883    istreambuf_iterator<char> file_begin(file_stream);
1884    istreambuf_iterator<char> file_end;
1885    return string(file_begin, file_end);
1886}
1887
1888typedef Keymaster1Test ImportKeyTest;
1889INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, ImportKeyTest, test_params);
1890
1891TEST_P(ImportKeyTest, RsaSuccess) {
1892    string pk8_key = read_file("rsa_privkey_pk8.der");
1893    ASSERT_EQ(633U, pk8_key.size());
1894
1895    ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
1896                                         .RsaSigningKey(1024, 65537)
1897                                         .Digest(KM_DIGEST_NONE)
1898                                         .Padding(KM_PAD_NONE),
1899                                     KM_KEY_FORMAT_PKCS8, pk8_key));
1900
1901    // Check values derived from the key.
1902    EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA) ? hw_enforced()
1903                                                                                 : sw_enforced(),
1904                         TAG_ALGORITHM, KM_ALGORITHM_RSA));
1905    EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA) ? hw_enforced()
1906                                                                                 : sw_enforced(),
1907                         TAG_KEY_SIZE, 1024));
1908    EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA) ? hw_enforced()
1909                                                                                 : sw_enforced(),
1910                         TAG_RSA_PUBLIC_EXPONENT, 65537U));
1911
1912    // And values provided by AndroidKeymaster
1913    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1914        EXPECT_TRUE(contains(hw_enforced(), TAG_ORIGIN, KM_ORIGIN_UNKNOWN));
1915    else
1916        EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
1917    EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
1918
1919    string message(1024 / 8, 'a');
1920    string signature;
1921    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
1922    VerifyMessage(message, signature, KM_DIGEST_NONE, KM_PAD_NONE);
1923
1924    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1925        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1926}
1927
1928TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
1929    string pk8_key = read_file("rsa_privkey_pk8.der");
1930    ASSERT_EQ(633U, pk8_key.size());
1931    ASSERT_EQ(KM_ERROR_IMPORT_PARAMETER_MISMATCH,
1932              ImportKey(AuthorizationSetBuilder()
1933                            .RsaSigningKey(2048 /* Doesn't match key */, 3)
1934                            .Digest(KM_DIGEST_NONE)
1935                            .Padding(KM_PAD_NONE),
1936                        KM_KEY_FORMAT_PKCS8, pk8_key));
1937
1938    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1939}
1940
1941TEST_P(ImportKeyTest, RsaPublicExponenMismatch) {
1942    string pk8_key = read_file("rsa_privkey_pk8.der");
1943    ASSERT_EQ(633U, pk8_key.size());
1944    ASSERT_EQ(KM_ERROR_IMPORT_PARAMETER_MISMATCH,
1945              ImportKey(AuthorizationSetBuilder()
1946                            .RsaSigningKey(256, 3 /* Doesnt' match key */)
1947                            .Digest(KM_DIGEST_NONE)
1948                            .Padding(KM_PAD_NONE),
1949                        KM_KEY_FORMAT_PKCS8, pk8_key));
1950
1951    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1952}
1953
1954TEST_P(ImportKeyTest, EcdsaSuccess) {
1955    string pk8_key = read_file("ec_privkey_pk8.der");
1956    ASSERT_EQ(138U, pk8_key.size());
1957
1958    ASSERT_EQ(KM_ERROR_OK,
1959              ImportKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(KM_DIGEST_NONE),
1960                        KM_KEY_FORMAT_PKCS8, pk8_key));
1961
1962    // Check values derived from the key.
1963    EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC) ? hw_enforced()
1964                                                                                : sw_enforced(),
1965                         TAG_ALGORITHM, KM_ALGORITHM_EC));
1966    EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC) ? hw_enforced()
1967                                                                                : sw_enforced(),
1968                         TAG_KEY_SIZE, 256));
1969
1970    // And values provided by AndroidKeymaster
1971    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1972        EXPECT_TRUE(contains(hw_enforced(), TAG_ORIGIN, KM_ORIGIN_UNKNOWN));
1973    else
1974        EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
1975    EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
1976
1977    string message(32, 'a');
1978    string signature;
1979    SignMessage(message, &signature, KM_DIGEST_NONE);
1980    VerifyMessage(message, signature, KM_DIGEST_NONE);
1981
1982    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1983        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1984}
1985
1986TEST_P(ImportKeyTest, EcdsaSizeSpecified) {
1987    string pk8_key = read_file("ec_privkey_pk8.der");
1988    ASSERT_EQ(138U, pk8_key.size());
1989
1990    ASSERT_EQ(KM_ERROR_OK,
1991              ImportKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(KM_DIGEST_NONE),
1992                        KM_KEY_FORMAT_PKCS8, pk8_key));
1993
1994    // Check values derived from the key.
1995    EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC) ? hw_enforced()
1996                                                                                : sw_enforced(),
1997                         TAG_ALGORITHM, KM_ALGORITHM_EC));
1998    EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC) ? hw_enforced()
1999                                                                                : sw_enforced(),
2000                         TAG_KEY_SIZE, 256));
2001
2002    // And values provided by AndroidKeymaster
2003    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
2004        EXPECT_TRUE(contains(hw_enforced(), TAG_ORIGIN, KM_ORIGIN_UNKNOWN));
2005    else
2006        EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
2007    EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
2008
2009    string message(32, 'a');
2010    string signature;
2011    SignMessage(message, &signature, KM_DIGEST_NONE);
2012    VerifyMessage(message, signature, KM_DIGEST_NONE);
2013
2014    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
2015        EXPECT_EQ(4, GetParam()->keymaster0_calls());
2016}
2017
2018TEST_P(ImportKeyTest, EcdsaSizeMismatch) {
2019    string pk8_key = read_file("ec_privkey_pk8.der");
2020    ASSERT_EQ(138U, pk8_key.size());
2021    ASSERT_EQ(KM_ERROR_IMPORT_PARAMETER_MISMATCH,
2022              ImportKey(AuthorizationSetBuilder()
2023                            .EcdsaSigningKey(224 /* Doesn't match key */)
2024                            .Digest(KM_DIGEST_NONE),
2025                        KM_KEY_FORMAT_PKCS8, pk8_key));
2026
2027    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2028}
2029
2030TEST_P(ImportKeyTest, AesKeySuccess) {
2031    char key_data[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2032    string key(key_data, sizeof(key_data));
2033    ASSERT_EQ(KM_ERROR_OK,
2034              ImportKey(AuthorizationSetBuilder().AesEncryptionKey(128).EcbMode().Authorization(
2035                            TAG_PADDING, KM_PAD_PKCS7),
2036                        KM_KEY_FORMAT_RAW, key));
2037
2038    EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
2039    EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
2040
2041    string message = "Hello World!";
2042    string ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_PKCS7);
2043    string plaintext = DecryptMessage(ciphertext, KM_MODE_ECB, KM_PAD_PKCS7);
2044    EXPECT_EQ(message, plaintext);
2045
2046    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2047}
2048
2049TEST_P(ImportKeyTest, HmacSha256KeySuccess) {
2050    char key_data[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2051    string key(key_data, sizeof(key_data));
2052    ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
2053                                         .HmacKey(sizeof(key_data) * 8)
2054                                         .Digest(KM_DIGEST_SHA_2_256)
2055                                         .Authorization(TAG_MIN_MAC_LENGTH, 256),
2056                                     KM_KEY_FORMAT_RAW, key));
2057
2058    EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
2059    EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
2060
2061    string message = "Hello World!";
2062    string signature;
2063    MacMessage(message, &signature, 256);
2064    VerifyMac(message, signature);
2065
2066    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2067}
2068
2069typedef Keymaster1Test EncryptionOperationsTest;
2070INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, EncryptionOperationsTest, test_params);
2071
2072TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
2073    ASSERT_EQ(KM_ERROR_OK,
2074              GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(256, 3).Padding(KM_PAD_NONE)));
2075
2076    string message = "12345678901234567890123456789012";
2077    string ciphertext1 = EncryptMessage(string(message), KM_PAD_NONE);
2078    EXPECT_EQ(256U / 8, ciphertext1.size());
2079
2080    string ciphertext2 = EncryptMessage(string(message), KM_PAD_NONE);
2081    EXPECT_EQ(256U / 8, ciphertext2.size());
2082
2083    // Unpadded RSA is deterministic
2084    EXPECT_EQ(ciphertext1, ciphertext2);
2085
2086    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2087        EXPECT_EQ(3, GetParam()->keymaster0_calls());
2088}
2089
2090TEST_P(EncryptionOperationsTest, RsaNoPaddingTooShort) {
2091    ASSERT_EQ(KM_ERROR_OK,
2092              GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(256, 3).Padding(KM_PAD_NONE)));
2093
2094    string message = "1";
2095
2096    string ciphertext = EncryptMessage(message, KM_PAD_NONE);
2097    EXPECT_EQ(256U / 8, ciphertext.size());
2098
2099    string expected_plaintext = string(256 / 8 - 1, 0) + message;
2100    string plaintext = DecryptMessage(ciphertext, KM_PAD_NONE);
2101
2102    EXPECT_EQ(expected_plaintext, plaintext);
2103
2104    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2105        EXPECT_EQ(4, GetParam()->keymaster0_calls());
2106}
2107
2108TEST_P(EncryptionOperationsTest, RsaNoPaddingTooLong) {
2109    ASSERT_EQ(KM_ERROR_OK,
2110              GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(256, 3).Padding(KM_PAD_NONE)));
2111
2112    string message = "123456789012345678901234567890123";
2113
2114    AuthorizationSet begin_params(client_params());
2115    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2116    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2117
2118    string result;
2119    size_t input_consumed;
2120    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, UpdateOperation(message, &result, &input_consumed));
2121
2122    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2123        EXPECT_EQ(2, GetParam()->keymaster0_calls());
2124}
2125
2126TEST_P(EncryptionOperationsTest, RsaNoPaddingLargerThanModulus) {
2127    ASSERT_EQ(KM_ERROR_OK,
2128              GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(256, 3).Padding(KM_PAD_NONE)));
2129
2130    string exported;
2131    ASSERT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &exported));
2132
2133    const uint8_t* p = reinterpret_cast<const uint8_t*>(exported.data());
2134    unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(
2135        d2i_PUBKEY(nullptr /* alloc new */, &p, exported.size()));
2136    unique_ptr<RSA, RSA_Delete> rsa(EVP_PKEY_get1_RSA(pkey.get()));
2137
2138    size_t modulus_len = BN_num_bytes(rsa->n);
2139    ASSERT_EQ(256U / 8, modulus_len);
2140    unique_ptr<uint8_t> modulus_buf(new uint8_t[modulus_len]);
2141    BN_bn2bin(rsa->n, modulus_buf.get());
2142
2143    // The modulus is too big to encrypt.
2144    string message(reinterpret_cast<const char*>(modulus_buf.get()), modulus_len);
2145
2146    AuthorizationSet begin_params(client_params());
2147    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2148    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2149
2150    string result;
2151    size_t input_consumed;
2152    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
2153    EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, FinishOperation(&result));
2154
2155    // One smaller than the modulus is okay.
2156    BN_sub(rsa->n, rsa->n, BN_value_one());
2157    modulus_len = BN_num_bytes(rsa->n);
2158    ASSERT_EQ(256U / 8, modulus_len);
2159    BN_bn2bin(rsa->n, modulus_buf.get());
2160    message = string(reinterpret_cast<const char*>(modulus_buf.get()), modulus_len);
2161    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2162    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
2163    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&result));
2164
2165    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2166        EXPECT_EQ(4, GetParam()->keymaster0_calls());
2167}
2168
2169TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
2170    size_t key_size = 768;
2171    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2172                                           .RsaEncryptionKey(key_size, 3)
2173                                           .Padding(KM_PAD_RSA_OAEP)
2174                                           .Digest(KM_DIGEST_SHA_2_256)));
2175
2176    string message = "Hello";
2177    string ciphertext1 = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
2178    EXPECT_EQ(key_size / 8, ciphertext1.size());
2179
2180    string ciphertext2 = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
2181    EXPECT_EQ(key_size / 8, ciphertext2.size());
2182
2183    // OAEP randomizes padding so every result should be different.
2184    EXPECT_NE(ciphertext1, ciphertext2);
2185
2186    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2187        EXPECT_EQ(3, GetParam()->keymaster0_calls());
2188}
2189
2190TEST_P(EncryptionOperationsTest, RsaOaepSha224Success) {
2191    size_t key_size = 768;
2192    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2193                                           .RsaEncryptionKey(key_size, 3)
2194                                           .Padding(KM_PAD_RSA_OAEP)
2195                                           .Digest(KM_DIGEST_SHA_2_224)));
2196
2197    string message = "Hello";
2198    string ciphertext1 = EncryptMessage(string(message), KM_DIGEST_SHA_2_224, KM_PAD_RSA_OAEP);
2199    EXPECT_EQ(key_size / 8, ciphertext1.size());
2200
2201    string ciphertext2 = EncryptMessage(string(message), KM_DIGEST_SHA_2_224, KM_PAD_RSA_OAEP);
2202    EXPECT_EQ(key_size / 8, ciphertext2.size());
2203
2204    // OAEP randomizes padding so every result should be different.
2205    EXPECT_NE(ciphertext1, ciphertext2);
2206
2207    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2208        EXPECT_EQ(3, GetParam()->keymaster0_calls());
2209}
2210
2211TEST_P(EncryptionOperationsTest, RsaOaepRoundTrip) {
2212    size_t key_size = 768;
2213    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2214                                           .RsaEncryptionKey(key_size, 3)
2215                                           .Padding(KM_PAD_RSA_OAEP)
2216                                           .Digest(KM_DIGEST_SHA_2_256)));
2217    string message = "Hello World!";
2218    string ciphertext = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
2219    EXPECT_EQ(key_size / 8, ciphertext.size());
2220
2221    string plaintext = DecryptMessage(ciphertext, KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
2222    EXPECT_EQ(message, plaintext);
2223
2224    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2225        EXPECT_EQ(4, GetParam()->keymaster0_calls());
2226}
2227
2228TEST_P(EncryptionOperationsTest, RsaOaepSha224RoundTrip) {
2229    size_t key_size = 768;
2230    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2231                                           .RsaEncryptionKey(key_size, 3)
2232                                           .Padding(KM_PAD_RSA_OAEP)
2233                                           .Digest(KM_DIGEST_SHA_2_224)));
2234    string message = "Hello World!";
2235    string ciphertext = EncryptMessage(string(message), KM_DIGEST_SHA_2_224, KM_PAD_RSA_OAEP);
2236    EXPECT_EQ(key_size / 8, ciphertext.size());
2237
2238    string plaintext = DecryptMessage(ciphertext, KM_DIGEST_SHA_2_224, KM_PAD_RSA_OAEP);
2239    EXPECT_EQ(message, plaintext);
2240
2241    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2242        EXPECT_EQ(4, GetParam()->keymaster0_calls());
2243}
2244
2245TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
2246    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2247                                           .RsaEncryptionKey(512, 3)
2248                                           .Padding(KM_PAD_RSA_OAEP)
2249                                           .Digest(KM_DIGEST_NONE)));
2250    string message = "Hello World!";
2251
2252    AuthorizationSet begin_params(client_params());
2253    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
2254    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
2255    EXPECT_EQ(KM_ERROR_INCOMPATIBLE_DIGEST, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2256
2257    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2258        EXPECT_EQ(2, GetParam()->keymaster0_calls());
2259}
2260
2261TEST_P(EncryptionOperationsTest, RsaOaepUnauthorizedDigest) {
2262    if (GetParam()->minimal_digest_set())
2263        // We don't have two supported digests, so we can't try authorizing one and using another.
2264        return;
2265
2266    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2267                                           .RsaEncryptionKey(512, 3)
2268                                           .Padding(KM_PAD_RSA_OAEP)
2269                                           .Digest(KM_DIGEST_SHA_2_256)));
2270    string message = "Hello World!";
2271    // Works because encryption is a public key operation.
2272    EncryptMessage(string(message), KM_DIGEST_SHA1, KM_PAD_RSA_OAEP);
2273
2274    AuthorizationSet begin_params(client_params());
2275    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
2276    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA1);
2277    EXPECT_EQ(KM_ERROR_INCOMPATIBLE_DIGEST, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2278
2279    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2280        EXPECT_EQ(3, GetParam()->keymaster0_calls());
2281}
2282
2283TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
2284    if (GetParam()->minimal_digest_set())
2285        // We don't have two supported digests, so we can't try encrypting with one and decrypting
2286        // with another.
2287        return;
2288
2289    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2290                                           .RsaEncryptionKey(768, 3)
2291                                           .Padding(KM_PAD_RSA_OAEP)
2292                                           .Digest(KM_DIGEST_SHA_2_256)
2293                                           .Digest(KM_DIGEST_SHA_2_384)));
2294    string message = "Hello World!";
2295    string ciphertext = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
2296
2297    string result;
2298    size_t input_consumed;
2299    AuthorizationSet begin_params(client_params());
2300    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
2301    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_384);
2302    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2303    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &result, &input_consumed));
2304    EXPECT_EQ(KM_ERROR_UNKNOWN_ERROR, FinishOperation(&result));
2305    EXPECT_EQ(0U, result.size());
2306
2307    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2308        EXPECT_EQ(4, GetParam()->keymaster0_calls());
2309}
2310
2311TEST_P(EncryptionOperationsTest, RsaOaepTooLarge) {
2312    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2313                                           .RsaEncryptionKey(512, 3)
2314                                           .Padding(KM_PAD_RSA_OAEP)
2315                                           .Digest(KM_DIGEST_SHA1)));
2316    string message = "12345678901234567890123";
2317    string result;
2318    size_t input_consumed;
2319
2320    AuthorizationSet begin_params(client_params());
2321    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
2322    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA1);
2323    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2324    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
2325    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(&result));
2326    EXPECT_EQ(0U, result.size());
2327
2328    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2329        EXPECT_EQ(2, GetParam()->keymaster0_calls());
2330}
2331
2332TEST_P(EncryptionOperationsTest, RsaOaepCorruptedDecrypt) {
2333    size_t key_size = 768;
2334    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2335                                           .RsaEncryptionKey(768, 3)
2336                                           .Padding(KM_PAD_RSA_OAEP)
2337                                           .Digest(KM_DIGEST_SHA_2_256)));
2338    string message = "Hello World!";
2339    string ciphertext = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
2340    EXPECT_EQ(key_size / 8, ciphertext.size());
2341
2342    // Corrupt the ciphertext
2343    ciphertext[key_size / 8 / 2]++;
2344
2345    string result;
2346    size_t input_consumed;
2347    AuthorizationSet begin_params(client_params());
2348    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
2349    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
2350    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2351    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &result, &input_consumed));
2352    EXPECT_EQ(KM_ERROR_UNKNOWN_ERROR, FinishOperation(&result));
2353    EXPECT_EQ(0U, result.size());
2354
2355    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2356        EXPECT_EQ(4, GetParam()->keymaster0_calls());
2357}
2358
2359TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
2360    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(512, 3).Padding(
2361                               KM_PAD_RSA_PKCS1_1_5_ENCRYPT)));
2362    string message = "Hello World!";
2363    string ciphertext1 = EncryptMessage(message, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
2364    EXPECT_EQ(512U / 8, ciphertext1.size());
2365
2366    string ciphertext2 = EncryptMessage(message, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
2367    EXPECT_EQ(512U / 8, ciphertext2.size());
2368
2369    // PKCS1 v1.5 randomizes padding so every result should be different.
2370    EXPECT_NE(ciphertext1, ciphertext2);
2371
2372    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2373        EXPECT_EQ(3, GetParam()->keymaster0_calls());
2374}
2375
2376TEST_P(EncryptionOperationsTest, RsaPkcs1RoundTrip) {
2377    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(512, 3).Padding(
2378                               KM_PAD_RSA_PKCS1_1_5_ENCRYPT)));
2379    string message = "Hello World!";
2380    string ciphertext = EncryptMessage(message, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
2381    EXPECT_EQ(512U / 8, ciphertext.size());
2382
2383    string plaintext = DecryptMessage(ciphertext, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
2384    EXPECT_EQ(message, plaintext);
2385
2386    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2387        EXPECT_EQ(4, GetParam()->keymaster0_calls());
2388}
2389
2390TEST_P(EncryptionOperationsTest, RsaRoundTripAllCombinations) {
2391    size_t key_size = 2048;
2392    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2393                                           .RsaEncryptionKey(key_size, 3)
2394                                           .Padding(KM_PAD_RSA_PKCS1_1_5_ENCRYPT)
2395                                           .Padding(KM_PAD_RSA_OAEP)
2396                                           .Digest(KM_DIGEST_NONE)
2397                                           .Digest(KM_DIGEST_MD5)
2398                                           .Digest(KM_DIGEST_SHA1)
2399                                           .Digest(KM_DIGEST_SHA_2_224)
2400                                           .Digest(KM_DIGEST_SHA_2_256)
2401                                           .Digest(KM_DIGEST_SHA_2_384)
2402                                           .Digest(KM_DIGEST_SHA_2_512)));
2403
2404    string message = "Hello World!";
2405
2406    keymaster_padding_t padding_modes[] = {KM_PAD_RSA_OAEP, KM_PAD_RSA_PKCS1_1_5_ENCRYPT};
2407    keymaster_digest_t digests[] = {
2408        KM_DIGEST_NONE,      KM_DIGEST_MD5,       KM_DIGEST_SHA1,      KM_DIGEST_SHA_2_224,
2409        KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512,
2410    };
2411
2412    for (auto padding : padding_modes)
2413        for (auto digest : digests) {
2414            if (padding == KM_PAD_RSA_OAEP && digest == KM_DIGEST_NONE)
2415                // OAEP requires a digest.
2416                continue;
2417
2418            string ciphertext = EncryptMessage(message, digest, padding);
2419            EXPECT_EQ(key_size / 8, ciphertext.size());
2420
2421            string plaintext = DecryptMessage(ciphertext, digest, padding);
2422            EXPECT_EQ(message, plaintext);
2423        }
2424
2425    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2426        EXPECT_EQ(40, GetParam()->keymaster0_calls());
2427}
2428
2429TEST_P(EncryptionOperationsTest, RsaPkcs1TooLarge) {
2430    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(512, 3).Padding(
2431                               KM_PAD_RSA_PKCS1_1_5_ENCRYPT)));
2432    string message = "123456789012345678901234567890123456789012345678901234";
2433    string result;
2434    size_t input_consumed;
2435
2436    AuthorizationSet begin_params(client_params());
2437    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
2438    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2439    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
2440    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(&result));
2441    EXPECT_EQ(0U, result.size());
2442
2443    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2444        EXPECT_EQ(2, GetParam()->keymaster0_calls());
2445}
2446
2447TEST_P(EncryptionOperationsTest, RsaPkcs1CorruptedDecrypt) {
2448    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(512, 3).Padding(
2449                               KM_PAD_RSA_PKCS1_1_5_ENCRYPT)));
2450    string message = "Hello World!";
2451    string ciphertext = EncryptMessage(string(message), KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
2452    EXPECT_EQ(512U / 8, ciphertext.size());
2453
2454    // Corrupt the ciphertext
2455    ciphertext[512 / 8 / 2]++;
2456
2457    string result;
2458    size_t input_consumed;
2459    AuthorizationSet begin_params(client_params());
2460    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
2461    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2462    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &result, &input_consumed));
2463    EXPECT_EQ(KM_ERROR_UNKNOWN_ERROR, FinishOperation(&result));
2464    EXPECT_EQ(0U, result.size());
2465
2466    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2467        EXPECT_EQ(4, GetParam()->keymaster0_calls());
2468}
2469
2470TEST_P(EncryptionOperationsTest, RsaEncryptWithSigningKey) {
2471    ASSERT_EQ(KM_ERROR_OK,
2472              GenerateKey(AuthorizationSetBuilder().RsaSigningKey(256, 3).Padding(KM_PAD_NONE)));
2473
2474    AuthorizationSet begin_params(client_params());
2475    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2476    ASSERT_EQ(KM_ERROR_INCOMPATIBLE_PURPOSE, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2477
2478    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2479        EXPECT_EQ(2, GetParam()->keymaster0_calls());
2480}
2481
2482TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
2483    ASSERT_EQ(KM_ERROR_OK,
2484              GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
2485    ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_ENCRYPT));
2486    ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_DECRYPT));
2487
2488    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
2489        EXPECT_EQ(3, GetParam()->keymaster0_calls());
2490}
2491
2492TEST_P(EncryptionOperationsTest, HmacEncrypt) {
2493    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2494                                           .HmacKey(128)
2495                                           .Digest(KM_DIGEST_SHA_2_256)
2496                                           .Padding(KM_PAD_NONE)
2497                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2498    ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_ENCRYPT));
2499    ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_DECRYPT));
2500
2501    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2502}
2503
2504TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
2505    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2506                                           .AesEncryptionKey(128)
2507                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
2508                                           .Padding(KM_PAD_NONE)));
2509    // Two-block message.
2510    string message = "12345678901234567890123456789012";
2511    string ciphertext1 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
2512    EXPECT_EQ(message.size(), ciphertext1.size());
2513
2514    string ciphertext2 = EncryptMessage(string(message), KM_MODE_ECB, KM_PAD_NONE);
2515    EXPECT_EQ(message.size(), ciphertext2.size());
2516
2517    // ECB is deterministic.
2518    EXPECT_EQ(ciphertext1, ciphertext2);
2519
2520    string plaintext = DecryptMessage(ciphertext1, KM_MODE_ECB, KM_PAD_NONE);
2521    EXPECT_EQ(message, plaintext);
2522
2523    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2524}
2525
2526TEST_P(EncryptionOperationsTest, AesEcbNotAuthorized) {
2527    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2528                                           .AesEncryptionKey(128)
2529                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
2530                                           .Padding(KM_PAD_NONE)));
2531    // Two-block message.
2532    string message = "12345678901234567890123456789012";
2533    AuthorizationSet begin_params(client_params());
2534    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
2535    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2536    EXPECT_EQ(KM_ERROR_INCOMPATIBLE_BLOCK_MODE, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2537
2538    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2539}
2540
2541TEST_P(EncryptionOperationsTest, AesEcbNoPaddingWrongInputSize) {
2542    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2543                                           .AesEncryptionKey(128)
2544                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
2545                                           .Padding(KM_PAD_NONE)));
2546    // Message is slightly shorter than two blocks.
2547    string message = "1234567890123456789012345678901";
2548
2549    AuthorizationSet begin_params(client_params());
2550    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
2551    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2552    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2553    string ciphertext;
2554    size_t input_consumed;
2555    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &ciphertext, &input_consumed));
2556    EXPECT_EQ(message.size(), input_consumed);
2557    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(&ciphertext));
2558
2559    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2560}
2561
2562TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
2563    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2564                                           .AesEncryptionKey(128)
2565                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
2566                                           .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
2567
2568    // Try various message lengths; all should work.
2569    for (size_t i = 0; i < 32; ++i) {
2570        string message(i, 'a');
2571        string ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_PKCS7);
2572        EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
2573        string plaintext = DecryptMessage(ciphertext, KM_MODE_ECB, KM_PAD_PKCS7);
2574        EXPECT_EQ(message, plaintext);
2575    }
2576
2577    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2578}
2579
2580TEST_P(EncryptionOperationsTest, AesEcbNoPaddingKeyWithPkcs7Padding) {
2581    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2582                                           .AesEncryptionKey(128)
2583                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
2584                                           .Authorization(TAG_PADDING, KM_PAD_NONE)));
2585
2586    // Try various message lengths; all should fail.
2587    for (size_t i = 0; i < 32; ++i) {
2588        AuthorizationSet begin_params(client_params());
2589        begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
2590        begin_params.push_back(TAG_PADDING, KM_PAD_PKCS7);
2591        EXPECT_EQ(KM_ERROR_INCOMPATIBLE_PADDING_MODE,
2592                  BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2593    }
2594
2595    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2596}
2597
2598TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
2599    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2600                                           .AesEncryptionKey(128)
2601                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
2602                                           .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
2603
2604    string message = "a";
2605    string ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_PKCS7);
2606    EXPECT_EQ(16U, ciphertext.size());
2607    EXPECT_NE(ciphertext, message);
2608    ++ciphertext[ciphertext.size() / 2];
2609
2610    AuthorizationSet begin_params(client_params());
2611    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
2612    begin_params.push_back(TAG_PADDING, KM_PAD_PKCS7);
2613    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2614    string plaintext;
2615    size_t input_consumed;
2616    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &plaintext, &input_consumed));
2617    EXPECT_EQ(ciphertext.size(), input_consumed);
2618    EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, FinishOperation(&plaintext));
2619
2620    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2621}
2622
2623TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
2624    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2625                                           .AesEncryptionKey(128)
2626                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
2627                                           .Padding(KM_PAD_NONE)));
2628    string message = "123";
2629    string iv1;
2630    string ciphertext1 = EncryptMessage(message, KM_MODE_CTR, KM_PAD_NONE, &iv1);
2631    EXPECT_EQ(message.size(), ciphertext1.size());
2632    EXPECT_EQ(16U, iv1.size());
2633
2634    string iv2;
2635    string ciphertext2 = EncryptMessage(message, KM_MODE_CTR, KM_PAD_NONE, &iv2);
2636    EXPECT_EQ(message.size(), ciphertext2.size());
2637    EXPECT_EQ(16U, iv2.size());
2638
2639    // IVs should be random, so ciphertexts should differ.
2640    EXPECT_NE(iv1, iv2);
2641    EXPECT_NE(ciphertext1, ciphertext2);
2642
2643    string plaintext = DecryptMessage(ciphertext1, KM_MODE_CTR, KM_PAD_NONE, iv1);
2644    EXPECT_EQ(message, plaintext);
2645
2646    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2647}
2648
2649TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
2650    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2651                                           .AesEncryptionKey(128)
2652                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
2653                                           .Padding(KM_PAD_NONE)));
2654
2655    int increment = 15;
2656    string message(239, 'a');
2657    AuthorizationSet input_params(client_params());
2658    input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
2659    input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2660    AuthorizationSet output_params;
2661    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, input_params, &output_params));
2662
2663    string ciphertext;
2664    size_t input_consumed;
2665    for (size_t i = 0; i < message.size(); i += increment)
2666        EXPECT_EQ(KM_ERROR_OK,
2667                  UpdateOperation(message.substr(i, increment), &ciphertext, &input_consumed));
2668    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
2669    EXPECT_EQ(message.size(), ciphertext.size());
2670
2671    // Move TAG_NONCE into input_params
2672    input_params.Reinitialize(output_params);
2673    input_params.push_back(client_params());
2674    input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
2675    input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2676    output_params.Clear();
2677
2678    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, input_params, &output_params));
2679    string plaintext;
2680    for (size_t i = 0; i < ciphertext.size(); i += increment)
2681        EXPECT_EQ(KM_ERROR_OK,
2682                  UpdateOperation(ciphertext.substr(i, increment), &plaintext, &input_consumed));
2683    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
2684    EXPECT_EQ(ciphertext.size(), plaintext.size());
2685    EXPECT_EQ(message, plaintext);
2686
2687    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2688}
2689
2690struct AesCtrSp80038aTestVector {
2691    const char* key;
2692    const char* nonce;
2693    const char* plaintext;
2694    const char* ciphertext;
2695};
2696
2697// These test vectors are taken from
2698// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
2699static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
2700    // AES-128
2701    {
2702        "2b7e151628aed2a6abf7158809cf4f3c", "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
2703        "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
2704        "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
2705        "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
2706        "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
2707    },
2708    // AES-192
2709    {
2710        "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b", "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
2711        "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
2712        "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
2713        "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
2714        "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
2715    },
2716    // AES-256
2717    {
2718        "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
2719        "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
2720        "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
2721        "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
2722        "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
2723        "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
2724    },
2725};
2726
2727TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
2728    for (size_t i = 0; i < 3; i++) {
2729        const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
2730        const string key = hex2str(test.key);
2731        const string nonce = hex2str(test.nonce);
2732        const string plaintext = hex2str(test.plaintext);
2733        const string ciphertext = hex2str(test.ciphertext);
2734        CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
2735    }
2736
2737    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2738}
2739
2740TEST_P(EncryptionOperationsTest, AesCtrInvalidPaddingMode) {
2741    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2742                                           .AesEncryptionKey(128)
2743                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
2744                                           .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
2745    AuthorizationSet begin_params(client_params());
2746    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
2747    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2748    EXPECT_EQ(KM_ERROR_INCOMPATIBLE_PADDING_MODE, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2749
2750    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2751}
2752
2753TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
2754    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2755                                           .AesEncryptionKey(128)
2756                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
2757                                           .Authorization(TAG_CALLER_NONCE)
2758                                           .Padding(KM_PAD_NONE)));
2759
2760    AuthorizationSet input_params(client_params());
2761    input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
2762    input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2763    input_params.push_back(TAG_NONCE, "123", 3);
2764    EXPECT_EQ(KM_ERROR_INVALID_NONCE, BeginOperation(KM_PURPOSE_ENCRYPT, input_params));
2765
2766    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2767}
2768
2769TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
2770    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2771                                           .AesEncryptionKey(128)
2772                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
2773                                           .Padding(KM_PAD_NONE)));
2774    // Two-block message.
2775    string message = "12345678901234567890123456789012";
2776    string iv1;
2777    string ciphertext1 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv1);
2778    EXPECT_EQ(message.size(), ciphertext1.size());
2779
2780    string iv2;
2781    string ciphertext2 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv2);
2782    EXPECT_EQ(message.size(), ciphertext2.size());
2783
2784    // IVs should be random, so ciphertexts should differ.
2785    EXPECT_NE(iv1, iv2);
2786    EXPECT_NE(ciphertext1, ciphertext2);
2787
2788    string plaintext = DecryptMessage(ciphertext1, KM_MODE_CBC, KM_PAD_NONE, iv1);
2789    EXPECT_EQ(message, plaintext);
2790
2791    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2792}
2793
2794TEST_P(EncryptionOperationsTest, AesCallerNonce) {
2795    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2796                                           .AesEncryptionKey(128)
2797                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
2798                                           .Authorization(TAG_CALLER_NONCE)
2799                                           .Padding(KM_PAD_NONE)));
2800    string message = "12345678901234567890123456789012";
2801    string iv1;
2802    // Don't specify nonce, should get a random one.
2803    string ciphertext1 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv1);
2804    EXPECT_EQ(message.size(), ciphertext1.size());
2805    EXPECT_EQ(16U, iv1.size());
2806
2807    string plaintext = DecryptMessage(ciphertext1, KM_MODE_CBC, KM_PAD_NONE, iv1);
2808    EXPECT_EQ(message, plaintext);
2809
2810    // Now specify a nonce, should also work.
2811    AuthorizationSet input_params(client_params());
2812    AuthorizationSet update_params;
2813    AuthorizationSet output_params;
2814    input_params.push_back(TAG_NONCE, "abcdefghijklmnop", 16);
2815    input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
2816    input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2817    string ciphertext2 =
2818        ProcessMessage(KM_PURPOSE_ENCRYPT, message, input_params, update_params, &output_params);
2819
2820    // Decrypt with correct nonce.
2821    plaintext = ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext2, input_params, update_params,
2822                               &output_params);
2823    EXPECT_EQ(message, plaintext);
2824
2825    // Now try with wrong nonce.
2826    input_params.Reinitialize(client_params());
2827    input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
2828    input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2829    input_params.push_back(TAG_NONCE, "aaaaaaaaaaaaaaaa", 16);
2830    plaintext = ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext2, input_params, update_params,
2831                               &output_params);
2832    EXPECT_NE(message, plaintext);
2833
2834    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2835}
2836
2837TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
2838    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2839                                           .AesEncryptionKey(128)
2840                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
2841                                           .Padding(KM_PAD_NONE)));
2842
2843    string message = "12345678901234567890123456789012";
2844    string iv1;
2845    // Don't specify nonce, should get a random one.
2846    string ciphertext1 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv1);
2847    EXPECT_EQ(message.size(), ciphertext1.size());
2848    EXPECT_EQ(16U, iv1.size());
2849
2850    string plaintext = DecryptMessage(ciphertext1, KM_MODE_CBC, KM_PAD_NONE, iv1);
2851    EXPECT_EQ(message, plaintext);
2852
2853    // Now specify a nonce, should fail.
2854    AuthorizationSet input_params(client_params());
2855    AuthorizationSet update_params;
2856    AuthorizationSet output_params;
2857    input_params.push_back(TAG_NONCE, "abcdefghijklmnop", 16);
2858    input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
2859    input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2860
2861    EXPECT_EQ(KM_ERROR_CALLER_NONCE_PROHIBITED,
2862              BeginOperation(KM_PURPOSE_ENCRYPT, input_params, &output_params));
2863
2864    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2865}
2866
2867TEST_P(EncryptionOperationsTest, AesCbcIncrementalNoPadding) {
2868    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2869                                           .AesEncryptionKey(128)
2870                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
2871                                           .Padding(KM_PAD_NONE)));
2872
2873    int increment = 15;
2874    string message(240, 'a');
2875    AuthorizationSet input_params(client_params());
2876    input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
2877    input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2878    AuthorizationSet output_params;
2879    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, input_params, &output_params));
2880
2881    string ciphertext;
2882    size_t input_consumed;
2883    for (size_t i = 0; i < message.size(); i += increment)
2884        EXPECT_EQ(KM_ERROR_OK,
2885                  UpdateOperation(message.substr(i, increment), &ciphertext, &input_consumed));
2886    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
2887    EXPECT_EQ(message.size(), ciphertext.size());
2888
2889    // Move TAG_NONCE into input_params
2890    input_params.Reinitialize(output_params);
2891    input_params.push_back(client_params());
2892    input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
2893    input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2894    output_params.Clear();
2895
2896    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, input_params, &output_params));
2897    string plaintext;
2898    for (size_t i = 0; i < ciphertext.size(); i += increment)
2899        EXPECT_EQ(KM_ERROR_OK,
2900                  UpdateOperation(ciphertext.substr(i, increment), &plaintext, &input_consumed));
2901    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
2902    EXPECT_EQ(ciphertext.size(), plaintext.size());
2903    EXPECT_EQ(message, plaintext);
2904
2905    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2906}
2907
2908TEST_P(EncryptionOperationsTest, AesCbcPkcs7Padding) {
2909    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2910                                           .AesEncryptionKey(128)
2911                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
2912                                           .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
2913
2914    // Try various message lengths; all should work.
2915    for (size_t i = 0; i < 32; ++i) {
2916        string message(i, 'a');
2917        string iv;
2918        string ciphertext = EncryptMessage(message, KM_MODE_CBC, KM_PAD_PKCS7, &iv);
2919        EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
2920        string plaintext = DecryptMessage(ciphertext, KM_MODE_CBC, KM_PAD_PKCS7, iv);
2921        EXPECT_EQ(message, plaintext);
2922    }
2923
2924    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2925}
2926
2927TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
2928    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2929                                           .AesEncryptionKey(128)
2930                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
2931                                           .Authorization(TAG_PADDING, KM_PAD_NONE)
2932                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2933    string aad = "foobar";
2934    string message = "123456789012345678901234567890123456";
2935    AuthorizationSet begin_params(client_params());
2936    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
2937    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2938    begin_params.push_back(TAG_MAC_LENGTH, 128);
2939
2940    AuthorizationSet update_params;
2941    update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
2942
2943    // Encrypt
2944    AuthorizationSet begin_out_params;
2945    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
2946    string ciphertext;
2947    size_t input_consumed;
2948    AuthorizationSet update_out_params;
2949    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
2950                                           &input_consumed));
2951    EXPECT_EQ(message.size(), input_consumed);
2952    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
2953
2954    // Grab nonce
2955    EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
2956    begin_params.push_back(begin_out_params);
2957
2958    // Decrypt.
2959    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2960    string plaintext;
2961    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
2962                                           &plaintext, &input_consumed));
2963    EXPECT_EQ(ciphertext.size(), input_consumed);
2964    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
2965
2966    EXPECT_EQ(message, plaintext);
2967    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2968}
2969
2970TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
2971    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2972                                           .AesEncryptionKey(128)
2973                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
2974                                           .Authorization(TAG_PADDING, KM_PAD_NONE)
2975                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2976    string aad = "foobar";
2977    string message = "123456789012345678901234567890123456";
2978    AuthorizationSet begin_params(client_params());
2979    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
2980    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2981    begin_params.push_back(TAG_MAC_LENGTH, 96);
2982
2983    AuthorizationSet update_params;
2984    update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
2985
2986    AuthorizationSet begin_out_params;
2987    EXPECT_EQ(KM_ERROR_INVALID_MAC_LENGTH,
2988              BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
2989
2990    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2991}
2992
2993TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
2994    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2995                                           .AesEncryptionKey(128)
2996                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
2997                                           .Authorization(TAG_PADDING, KM_PAD_NONE)
2998                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2999    string aad = "foobar";
3000    string message = "123456789012345678901234567890123456";
3001    AuthorizationSet begin_params(client_params());
3002    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
3003    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3004    begin_params.push_back(TAG_MAC_LENGTH, 128);
3005
3006    AuthorizationSet update_params;
3007    update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3008
3009    // Encrypt
3010    AuthorizationSet begin_out_params;
3011    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
3012    string ciphertext;
3013    size_t input_consumed;
3014    AuthorizationSet update_out_params;
3015    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
3016                                           &input_consumed));
3017    EXPECT_EQ(message.size(), input_consumed);
3018    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
3019
3020    // Grab nonce
3021    EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
3022    begin_params.Reinitialize(client_params());
3023    begin_params.push_back(begin_out_params);
3024    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
3025    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3026    begin_params.push_back(TAG_MAC_LENGTH, 96);
3027
3028    // Decrypt.
3029    EXPECT_EQ(KM_ERROR_INVALID_MAC_LENGTH, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
3030
3031    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3032}
3033
3034TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
3035    uint8_t nonce[] = {
3036        0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
3037    };
3038    uint8_t ciphertext[] = {
3039        0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc, 0xd2, 0xcb, 0x16,
3040        0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78, 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a,
3041        0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d, 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76,
3042        0x76, 0x5e, 0xfb, 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
3043        0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
3044    };
3045    string ciphertext_str(reinterpret_cast<char*>(ciphertext), sizeof(ciphertext));
3046
3047    AuthorizationSet begin_params(client_params());
3048    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
3049    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3050    begin_params.push_back(TAG_MAC_LENGTH, 128);
3051    begin_params.push_back(TAG_NONCE, nonce, sizeof(nonce));
3052
3053    string plaintext;
3054    size_t input_consumed;
3055
3056    // Import correct key and decrypt
3057    uint8_t good_key[] = {
3058        0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
3059        0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
3060    };
3061    string good_key_str(reinterpret_cast<char*>(good_key), sizeof(good_key));
3062    ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
3063                                         .AesEncryptionKey(128)
3064                                         .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
3065                                         .Authorization(TAG_PADDING, KM_PAD_NONE)
3066                                         .Authorization(TAG_CALLER_NONCE)
3067                                         .Authorization(TAG_MIN_MAC_LENGTH, 128),
3068                                     KM_KEY_FORMAT_RAW, good_key_str));
3069    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
3070    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext_str, &plaintext, &input_consumed));
3071    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
3072
3073    // Import bad key and decrypt
3074    uint8_t bad_key[] = {
3075        0xbb, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
3076        0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
3077    };
3078    string bad_key_str(reinterpret_cast<char*>(bad_key), sizeof(bad_key));
3079    ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
3080                                         .AesEncryptionKey(128)
3081                                         .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
3082                                         .Authorization(TAG_PADDING, KM_PAD_NONE)
3083                                         .Authorization(TAG_MIN_MAC_LENGTH, 128),
3084                                     KM_KEY_FORMAT_RAW, bad_key_str));
3085    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
3086    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext_str, &plaintext, &input_consumed));
3087    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(&plaintext));
3088
3089    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3090}
3091
3092TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
3093    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3094                                           .AesEncryptionKey(128)
3095                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
3096                                           .Authorization(TAG_PADDING, KM_PAD_NONE)
3097                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3098    string aad = "123456789012345678";
3099    string empty_message;
3100    AuthorizationSet begin_params(client_params());
3101    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
3102    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3103    begin_params.push_back(TAG_MAC_LENGTH, 128);
3104
3105    AuthorizationSet update_params;
3106    update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3107
3108    // Encrypt
3109    AuthorizationSet begin_out_params;
3110    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
3111    string ciphertext;
3112    size_t input_consumed;
3113    AuthorizationSet update_out_params;
3114    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, empty_message, &update_out_params,
3115                                           &ciphertext, &input_consumed));
3116    EXPECT_EQ(0U, input_consumed);
3117    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
3118
3119    // Grab nonce
3120    EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
3121    begin_params.push_back(begin_out_params);
3122
3123    // Decrypt.
3124    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
3125    string plaintext;
3126    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
3127                                           &plaintext, &input_consumed));
3128    EXPECT_EQ(ciphertext.size(), input_consumed);
3129    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
3130
3131    EXPECT_EQ(empty_message, plaintext);
3132    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3133}
3134
3135TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
3136    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3137                                           .AesEncryptionKey(128)
3138                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
3139                                           .Authorization(TAG_PADDING, KM_PAD_NONE)
3140                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3141    AuthorizationSet begin_params(client_params());
3142    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
3143    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3144    begin_params.push_back(TAG_MAC_LENGTH, 128);
3145
3146    AuthorizationSet update_params;
3147    update_params.push_back(TAG_ASSOCIATED_DATA, "b", 1);
3148
3149    // Encrypt
3150    AuthorizationSet begin_out_params;
3151    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
3152    string ciphertext;
3153    size_t input_consumed;
3154    AuthorizationSet update_out_params;
3155
3156    // Send AAD, incrementally
3157    for (int i = 0; i < 1000; ++i) {
3158        EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, "", &update_out_params, &ciphertext,
3159                                               &input_consumed));
3160        EXPECT_EQ(0U, input_consumed);
3161        EXPECT_EQ(0U, ciphertext.size());
3162    }
3163
3164    // Now send data, incrementally, no data.
3165    AuthorizationSet empty_params;
3166    for (int i = 0; i < 1000; ++i) {
3167        EXPECT_EQ(KM_ERROR_OK, UpdateOperation(empty_params, "a", &update_out_params, &ciphertext,
3168                                               &input_consumed));
3169        EXPECT_EQ(1U, input_consumed);
3170    }
3171    EXPECT_EQ(1000U, ciphertext.size());
3172
3173    // And finish.
3174    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
3175    EXPECT_EQ(1016U, ciphertext.size());
3176
3177    // Grab nonce
3178    EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
3179    begin_params.push_back(begin_out_params);
3180
3181    // Decrypt.
3182    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
3183    string plaintext;
3184
3185    // Send AAD, incrementally, no data
3186    for (int i = 0; i < 1000; ++i) {
3187        EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, "", &update_out_params, &plaintext,
3188                                               &input_consumed));
3189        EXPECT_EQ(0U, input_consumed);
3190        EXPECT_EQ(0U, plaintext.size());
3191    }
3192
3193    // Now send data, incrementally.
3194    for (size_t i = 0; i < ciphertext.length(); ++i) {
3195        EXPECT_EQ(KM_ERROR_OK, UpdateOperation(empty_params, string(ciphertext.data() + i, 1),
3196                                               &update_out_params, &plaintext, &input_consumed));
3197        EXPECT_EQ(1U, input_consumed);
3198    }
3199    EXPECT_EQ(1000U, plaintext.size());
3200    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
3201
3202    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3203}
3204
3205TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
3206    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3207                                           .AesEncryptionKey(128)
3208                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
3209                                           .Authorization(TAG_PADDING, KM_PAD_NONE)
3210                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3211    string message = "123456789012345678901234567890123456";
3212    AuthorizationSet begin_params(client_params());
3213    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
3214    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3215    begin_params.push_back(TAG_MAC_LENGTH, 128);
3216    AuthorizationSet begin_out_params;
3217
3218    AuthorizationSet update_params;
3219    update_params.push_back(TAG_ASSOCIATED_DATA, "foo", 3);
3220
3221    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
3222
3223    // No data, AAD only.
3224    string ciphertext;
3225    size_t input_consumed;
3226    AuthorizationSet update_out_params;
3227    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, "" /* message */, &update_out_params,
3228                                           &ciphertext, &input_consumed));
3229    EXPECT_EQ(0U, input_consumed);
3230
3231    // AAD and data.
3232    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
3233                                           &input_consumed));
3234    EXPECT_EQ(message.size(), input_consumed);
3235    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
3236
3237    // Grab nonce.
3238    EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
3239    begin_params.push_back(begin_out_params);
3240
3241    // Decrypt
3242    update_params.Clear();
3243    update_params.push_back(TAG_ASSOCIATED_DATA, "foofoo", 6);
3244
3245    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
3246    string plaintext;
3247    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
3248                                           &plaintext, &input_consumed));
3249    EXPECT_EQ(ciphertext.size(), input_consumed);
3250    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
3251
3252    EXPECT_EQ(message, plaintext);
3253    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3254}
3255
3256TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
3257    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3258                                           .AesEncryptionKey(128)
3259                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
3260                                           .Authorization(TAG_PADDING, KM_PAD_NONE)
3261                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3262    string message = "12345678901234567890123456789012";
3263    AuthorizationSet begin_params(client_params());
3264    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
3265    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3266    begin_params.push_back(TAG_MAC_LENGTH, 128);
3267
3268    AuthorizationSet update_params;
3269    update_params.push_back(TAG_ASSOCIATED_DATA, "foobar", 6);
3270
3271    AuthorizationSet finish_params;
3272    AuthorizationSet finish_out_params;
3273
3274    // Encrypt
3275    AuthorizationSet begin_out_params;
3276    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
3277    AuthorizationSet update_out_params;
3278    string ciphertext;
3279    size_t input_consumed;
3280    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
3281                                           &input_consumed));
3282    EXPECT_EQ(message.size(), input_consumed);
3283    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
3284
3285    // Grab nonce
3286    EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
3287    begin_params.push_back(begin_out_params);
3288
3289    update_params.Clear();
3290    update_params.push_back(TAG_ASSOCIATED_DATA, "barfoo" /* Wrong AAD */, 6);
3291
3292    // Decrypt.
3293    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params, &begin_out_params));
3294    string plaintext;
3295    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
3296                                           &plaintext, &input_consumed));
3297    EXPECT_EQ(ciphertext.size(), input_consumed);
3298    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(&plaintext));
3299
3300    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3301}
3302
3303TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
3304    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3305                                           .AesEncryptionKey(128)
3306                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
3307                                           .Authorization(TAG_PADDING, KM_PAD_NONE)
3308                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3309    string message = "12345678901234567890123456789012";
3310    AuthorizationSet begin_params(client_params());
3311    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
3312    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3313    begin_params.push_back(TAG_MAC_LENGTH, 128);
3314
3315    AuthorizationSet update_params;
3316    update_params.push_back(TAG_ASSOCIATED_DATA, "foobar", 6);
3317
3318    // Encrypt
3319    AuthorizationSet begin_out_params;
3320    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
3321    AuthorizationSet update_out_params;
3322    string ciphertext;
3323    size_t input_consumed;
3324    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
3325                                           &input_consumed));
3326    EXPECT_EQ(message.size(), input_consumed);
3327    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
3328
3329    begin_params.push_back(TAG_NONCE, "123456789012", 12);
3330
3331    // Decrypt
3332    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params, &begin_out_params));
3333    string plaintext;
3334    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
3335                                           &plaintext, &input_consumed));
3336    EXPECT_EQ(ciphertext.size(), input_consumed);
3337    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(&plaintext));
3338
3339    // With wrong nonce, should have gotten garbage plaintext.
3340    EXPECT_NE(message, plaintext);
3341    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3342}
3343
3344TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
3345    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3346                                           .AesEncryptionKey(128)
3347                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
3348                                           .Authorization(TAG_PADDING, KM_PAD_NONE)
3349                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3350    string aad = "foobar";
3351    string message = "123456789012345678901234567890123456";
3352    AuthorizationSet begin_params(client_params());
3353    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
3354    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3355    begin_params.push_back(TAG_MAC_LENGTH, 128);
3356    AuthorizationSet begin_out_params;
3357
3358    AuthorizationSet update_params;
3359    update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3360
3361    // Encrypt
3362    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
3363    AuthorizationSet update_out_params;
3364    string ciphertext;
3365    size_t input_consumed;
3366    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
3367                                           &input_consumed));
3368    EXPECT_EQ(message.size(), input_consumed);
3369    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
3370
3371    // Corrupt tag
3372    (*ciphertext.rbegin())++;
3373
3374    // Grab nonce.
3375    EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
3376    begin_params.push_back(begin_out_params);
3377
3378    // Decrypt.
3379    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params, &begin_out_params));
3380    string plaintext;
3381    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
3382                                           &plaintext, &input_consumed));
3383    EXPECT_EQ(ciphertext.size(), input_consumed);
3384    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(&plaintext));
3385
3386    EXPECT_EQ(message, plaintext);
3387    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3388}
3389
3390typedef Keymaster1Test MaxOperationsTest;
3391INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, MaxOperationsTest, test_params);
3392
3393TEST_P(MaxOperationsTest, TestLimit) {
3394    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3395                                           .AesEncryptionKey(128)
3396                                           .EcbMode()
3397                                           .Authorization(TAG_PADDING, KM_PAD_NONE)
3398                                           .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
3399
3400    string message = "1234567890123456";
3401    string ciphertext1 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
3402    string ciphertext2 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
3403    string ciphertext3 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
3404
3405    // Fourth time should fail.
3406    AuthorizationSet begin_params(client_params());
3407    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
3408    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3409    EXPECT_EQ(KM_ERROR_KEY_MAX_OPS_EXCEEDED, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
3410
3411    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3412}
3413
3414TEST_P(MaxOperationsTest, TestAbort) {
3415    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3416                                           .AesEncryptionKey(128)
3417                                           .EcbMode()
3418                                           .Authorization(TAG_PADDING, KM_PAD_NONE)
3419                                           .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
3420
3421    string message = "1234567890123456";
3422    string ciphertext1 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
3423    string ciphertext2 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
3424    string ciphertext3 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
3425
3426    // Fourth time should fail.
3427    AuthorizationSet begin_params(client_params());
3428    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
3429    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3430    EXPECT_EQ(KM_ERROR_KEY_MAX_OPS_EXCEEDED, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
3431
3432    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3433}
3434
3435typedef Keymaster1Test AddEntropyTest;
3436INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, AddEntropyTest, test_params);
3437
3438TEST_P(AddEntropyTest, AddEntropy) {
3439    // There's no obvious way to test that entropy is actually added, but we can test that the API
3440    // doesn't blow up or return an error.
3441    EXPECT_EQ(KM_ERROR_OK,
3442              device()->add_rng_entropy(device(), reinterpret_cast<const uint8_t*>("foo"), 3));
3443
3444    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3445}
3446
3447typedef Keymaster1Test Keymaster0AdapterTest;
3448INSTANTIATE_TEST_CASE_P(
3449    AndroidKeymasterTest, Keymaster0AdapterTest,
3450    ::testing::Values(
3451        InstanceCreatorPtr(new Keymaster0AdapterTestInstanceCreator(true /* support_ec */)),
3452        InstanceCreatorPtr(new Keymaster0AdapterTestInstanceCreator(false /* support_ec */))));
3453
3454TEST_P(Keymaster0AdapterTest, OldSoftwareKeymaster1RsaBlob) {
3455    // Load and use an old-style Keymaster1 software key blob.  These blobs contain OCB-encrypted
3456    // key data.
3457    string km1_sw = read_file("km1_sw_rsa_512.blob");
3458    EXPECT_EQ(486U, km1_sw.length());
3459
3460    uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km1_sw.length()));
3461    memcpy(key_data, km1_sw.data(), km1_sw.length());
3462    set_key_blob(key_data, km1_sw.length());
3463
3464    string message(64, 'a');
3465    string signature;
3466    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
3467
3468    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3469}
3470
3471TEST_P(Keymaster0AdapterTest, UnversionedSoftwareKeymaster1RsaBlob) {
3472    // Load and use an old-style Keymaster1 software key blob, without the version byte.  These
3473    // blobs contain OCB-encrypted key data.
3474    string km1_sw = read_file("km1_sw_rsa_512_unversioned.blob");
3475    EXPECT_EQ(477U, km1_sw.length());
3476
3477    uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km1_sw.length()));
3478    memcpy(key_data, km1_sw.data(), km1_sw.length());
3479    set_key_blob(key_data, km1_sw.length());
3480
3481    string message(64, 'a');
3482    string signature;
3483    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
3484
3485    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3486}
3487
3488TEST_P(Keymaster0AdapterTest, OldSoftwareKeymaster1EcdsaBlob) {
3489    // Load and use an old-style Keymaster1 software key blob.  These blobs contain OCB-encrypted
3490    // key data.
3491    string km1_sw = read_file("km1_sw_ecdsa_256.blob");
3492    EXPECT_EQ(270U, km1_sw.length());
3493
3494    uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km1_sw.length()));
3495    memcpy(key_data, km1_sw.data(), km1_sw.length());
3496    set_key_blob(key_data, km1_sw.length());
3497
3498    string message(32, static_cast<char>(0xFF));
3499    string signature;
3500    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
3501
3502    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3503}
3504
3505struct Malloc_Delete {
3506    void operator()(void* p) { free(p); }
3507};
3508
3509TEST_P(Keymaster0AdapterTest, OldSoftwareKeymaster0RsaBlob) {
3510    // Load and use an old softkeymaster blob.  These blobs contain PKCS#8 key data.
3511    string km0_sw = read_file("km0_sw_rsa_512.blob");
3512    EXPECT_EQ(333U, km0_sw.length());
3513
3514    uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km0_sw.length()));
3515    memcpy(key_data, km0_sw.data(), km0_sw.length());
3516    set_key_blob(key_data, km0_sw.length());
3517
3518    string message(64, 'a');
3519    string signature;
3520    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
3521
3522    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3523}
3524
3525TEST_P(Keymaster0AdapterTest, OldSwKeymaster0RsaBlobGetCharacteristics) {
3526    // Load and use an old softkeymaster blob.  These blobs contain PKCS#8 key data.
3527    string km0_sw = read_file("km0_sw_rsa_512.blob");
3528    EXPECT_EQ(333U, km0_sw.length());
3529
3530    uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km0_sw.length()));
3531    memcpy(key_data, km0_sw.data(), km0_sw.length());
3532    set_key_blob(key_data, km0_sw.length());
3533
3534    EXPECT_EQ(KM_ERROR_OK, GetCharacteristics());
3535    EXPECT_TRUE(contains(sw_enforced(), TAG_ALGORITHM, KM_ALGORITHM_RSA));
3536    EXPECT_TRUE(contains(sw_enforced(), TAG_KEY_SIZE, 512));
3537    EXPECT_TRUE(contains(sw_enforced(), TAG_RSA_PUBLIC_EXPONENT, 3));
3538    EXPECT_TRUE(contains(sw_enforced(), TAG_DIGEST, KM_DIGEST_NONE));
3539    EXPECT_TRUE(contains(sw_enforced(), TAG_PADDING, KM_PAD_NONE));
3540    EXPECT_TRUE(contains(sw_enforced(), TAG_PURPOSE, KM_PURPOSE_SIGN));
3541    EXPECT_TRUE(contains(sw_enforced(), TAG_PURPOSE, KM_PURPOSE_VERIFY));
3542    EXPECT_TRUE(sw_enforced().GetTagValue(TAG_ALL_USERS));
3543    EXPECT_TRUE(sw_enforced().GetTagValue(TAG_NO_AUTH_REQUIRED));
3544
3545    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3546}
3547
3548TEST_P(Keymaster0AdapterTest, OldHwKeymaster0RsaBlob) {
3549    // Load and use an old softkeymaster blob.  These blobs contain PKCS#8 key data.
3550    string km0_sw = read_file("km0_sw_rsa_512.blob");
3551    EXPECT_EQ(333U, km0_sw.length());
3552
3553    // The keymaster0 wrapper swaps the old softkeymaster leading 'P' for a 'Q' to make the key not
3554    // be recognized as a software key.  Do the same here to pretend this is a hardware key.
3555    EXPECT_EQ('P', km0_sw[0]);
3556    km0_sw[0] = 'Q';
3557
3558    uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km0_sw.length()));
3559    memcpy(key_data, km0_sw.data(), km0_sw.length());
3560    set_key_blob(key_data, km0_sw.length());
3561
3562    string message(64, 'a');
3563    string signature;
3564    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
3565    VerifyMessage(message, signature, KM_DIGEST_NONE, KM_PAD_NONE);
3566
3567    EXPECT_EQ(5, GetParam()->keymaster0_calls());
3568}
3569
3570TEST_P(Keymaster0AdapterTest, OldHwKeymaster0RsaBlobGetCharacteristics) {
3571    // Load and use an old softkeymaster blob.  These blobs contain PKCS#8 key data.
3572    string km0_sw = read_file("km0_sw_rsa_512.blob");
3573    EXPECT_EQ(333U, km0_sw.length());
3574
3575    // The keymaster0 wrapper swaps the old softkeymaster leading 'P' for a 'Q' to make the key not
3576    // be recognized as a software key.  Do the same here to pretend this is a hardware key.
3577    EXPECT_EQ('P', km0_sw[0]);
3578    km0_sw[0] = 'Q';
3579
3580    uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km0_sw.length()));
3581    memcpy(key_data, km0_sw.data(), km0_sw.length());
3582    set_key_blob(key_data, km0_sw.length());
3583
3584    EXPECT_EQ(KM_ERROR_OK, GetCharacteristics());
3585    EXPECT_TRUE(contains(hw_enforced(), TAG_ALGORITHM, KM_ALGORITHM_RSA));
3586    EXPECT_TRUE(contains(hw_enforced(), TAG_KEY_SIZE, 512));
3587    EXPECT_TRUE(contains(hw_enforced(), TAG_RSA_PUBLIC_EXPONENT, 3));
3588    EXPECT_TRUE(contains(hw_enforced(), TAG_DIGEST, KM_DIGEST_NONE));
3589    EXPECT_TRUE(contains(hw_enforced(), TAG_DIGEST, KM_DIGEST_MD5));
3590    EXPECT_TRUE(contains(hw_enforced(), TAG_DIGEST, KM_DIGEST_SHA1));
3591    EXPECT_TRUE(contains(hw_enforced(), TAG_DIGEST, KM_DIGEST_SHA_2_224));
3592    EXPECT_TRUE(contains(hw_enforced(), TAG_DIGEST, KM_DIGEST_SHA_2_256));
3593    EXPECT_TRUE(contains(hw_enforced(), TAG_DIGEST, KM_DIGEST_SHA_2_384));
3594    EXPECT_TRUE(contains(hw_enforced(), TAG_DIGEST, KM_DIGEST_SHA_2_512));
3595    EXPECT_TRUE(contains(hw_enforced(), TAG_PADDING, KM_PAD_NONE));
3596    EXPECT_TRUE(contains(hw_enforced(), TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT));
3597    EXPECT_TRUE(contains(hw_enforced(), TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN));
3598    EXPECT_TRUE(contains(hw_enforced(), TAG_PADDING, KM_PAD_RSA_OAEP));
3599    EXPECT_TRUE(contains(hw_enforced(), TAG_PADDING, KM_PAD_RSA_PSS));
3600    EXPECT_EQ(15U, hw_enforced().size());
3601
3602    EXPECT_TRUE(contains(sw_enforced(), TAG_PURPOSE, KM_PURPOSE_SIGN));
3603    EXPECT_TRUE(contains(sw_enforced(), TAG_PURPOSE, KM_PURPOSE_VERIFY));
3604    EXPECT_TRUE(sw_enforced().GetTagValue(TAG_ALL_USERS));
3605    EXPECT_TRUE(sw_enforced().GetTagValue(TAG_NO_AUTH_REQUIRED));
3606
3607    EXPECT_FALSE(contains(sw_enforced(), TAG_ALGORITHM, KM_ALGORITHM_RSA));
3608    EXPECT_FALSE(contains(sw_enforced(), TAG_KEY_SIZE, 512));
3609    EXPECT_FALSE(contains(sw_enforced(), TAG_RSA_PUBLIC_EXPONENT, 3));
3610    EXPECT_FALSE(contains(sw_enforced(), TAG_DIGEST, KM_DIGEST_NONE));
3611    EXPECT_FALSE(contains(sw_enforced(), TAG_PADDING, KM_PAD_NONE));
3612
3613    EXPECT_EQ(1, GetParam()->keymaster0_calls());
3614}
3615
3616TEST(SoftKeymasterWrapperTest, CheckKeymaster1Device) {
3617    // Make a good fake device, and wrap it.
3618    SoftKeymasterDevice* good_fake(new SoftKeymasterDevice(new TestKeymasterContext));
3619
3620    // Wrap it and check it.
3621    SoftKeymasterDevice* good_fake_wrapper(new SoftKeymasterDevice(new TestKeymasterContext));
3622    good_fake_wrapper->SetHardwareDevice(good_fake->keymaster_device());
3623    EXPECT_TRUE(good_fake_wrapper->Keymaster1DeviceIsGood());
3624
3625    // Close and clean up wrapper and wrapped
3626    good_fake_wrapper->keymaster_device()->common.close(good_fake_wrapper->hw_device());
3627
3628    // Make a "bad" (doesn't support all digests) device;
3629    keymaster1_device_t* sha256_only_fake = make_device_sha256_only(
3630        (new SoftKeymasterDevice(new TestKeymasterContext("256")))->keymaster_device());
3631
3632    // Wrap it and check it.
3633    SoftKeymasterDevice* sha256_only_fake_wrapper(
3634        (new SoftKeymasterDevice(new TestKeymasterContext)));
3635    sha256_only_fake_wrapper->SetHardwareDevice(sha256_only_fake);
3636    EXPECT_FALSE(sha256_only_fake_wrapper->Keymaster1DeviceIsGood());
3637
3638    // Close and clean up wrapper and wrapped
3639    sha256_only_fake_wrapper->keymaster_device()->common.close(
3640        sha256_only_fake_wrapper->hw_device());
3641}
3642
3643}  // namespace test
3644}  // namespace keymaster
3645