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