1/*
2 * Copyright 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "hmac_operation.h"
18
19#include <new>
20
21#include <openssl/evp.h>
22#include <openssl/hmac.h>
23
24#include "hmac_key.h"
25#include "openssl_err.h"
26
27#if defined(OPENSSL_IS_BORINGSSL)
28#include <openssl/mem.h>
29typedef size_t openssl_size_t;
30#else
31typedef int openssl_size_t;
32#endif
33
34namespace keymaster {
35
36Operation* HmacOperationFactory::CreateOperation(const Key& key,
37                                                 const AuthorizationSet& begin_params,
38                                                 keymaster_error_t* error) {
39    uint32_t min_mac_length_bits;
40    if (!key.authorizations().GetTagValue(TAG_MIN_MAC_LENGTH, &min_mac_length_bits)) {
41        LOG_E("HMAC key must have KM_TAG_MIN_MAC_LENGTH", 0);
42        *error = KM_ERROR_INVALID_KEY_BLOB;
43        return nullptr;
44    }
45
46    uint32_t mac_length_bits = UINT32_MAX;
47    if (begin_params.GetTagValue(TAG_MAC_LENGTH, &mac_length_bits)) {
48        if (purpose() == KM_PURPOSE_VERIFY) {
49            LOG_E("MAC length may not be specified for verify", 0);
50            *error = KM_ERROR_INVALID_ARGUMENT;
51            return nullptr;
52        }
53    } else {
54        if (purpose() == KM_PURPOSE_SIGN) {
55            *error = KM_ERROR_MISSING_MAC_LENGTH;
56            return nullptr;
57        }
58    }
59
60    keymaster_digest_t digest;
61    if (!key.authorizations().GetTagValue(TAG_DIGEST, &digest)) {
62        LOG_E("%d digests found in HMAC key authorizations; must be exactly 1",
63              begin_params.GetTagCount(TAG_DIGEST));
64        *error = KM_ERROR_INVALID_KEY_BLOB;
65        return nullptr;
66    }
67
68    const SymmetricKey* symmetric_key = static_cast<const SymmetricKey*>(&key);
69    UniquePtr<HmacOperation> op(new (std::nothrow) HmacOperation(
70        purpose(), symmetric_key->key_data(), symmetric_key->key_data_size(), digest,
71        mac_length_bits / 8, min_mac_length_bits / 8));
72    if (!op.get())
73        *error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
74    else
75        *error = op->error();
76
77    if (*error != KM_ERROR_OK)
78        return nullptr;
79
80    return op.release();
81}
82
83static keymaster_digest_t supported_digests[] = {KM_DIGEST_SHA1, KM_DIGEST_SHA_2_224,
84                                                 KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384,
85                                                 KM_DIGEST_SHA_2_512};
86const keymaster_digest_t* HmacOperationFactory::SupportedDigests(size_t* digest_count) const {
87    *digest_count = array_length(supported_digests);
88    return supported_digests;
89}
90
91HmacOperation::HmacOperation(keymaster_purpose_t purpose, const uint8_t* key_data,
92                             size_t key_data_size, keymaster_digest_t digest, size_t mac_length,
93                             size_t min_mac_length)
94    : Operation(purpose), error_(KM_ERROR_OK), mac_length_(mac_length),
95      min_mac_length_(min_mac_length) {
96    // Initialize CTX first, so dtor won't crash even if we error out later.
97    HMAC_CTX_init(&ctx_);
98
99    const EVP_MD* md = nullptr;
100    switch (digest) {
101    case KM_DIGEST_NONE:
102    case KM_DIGEST_MD5:
103        error_ = KM_ERROR_UNSUPPORTED_DIGEST;
104        break;
105    case KM_DIGEST_SHA1:
106        md = EVP_sha1();
107        break;
108    case KM_DIGEST_SHA_2_224:
109        md = EVP_sha224();
110        break;
111    case KM_DIGEST_SHA_2_256:
112        md = EVP_sha256();
113        break;
114    case KM_DIGEST_SHA_2_384:
115        md = EVP_sha384();
116        break;
117    case KM_DIGEST_SHA_2_512:
118        md = EVP_sha512();
119        break;
120    }
121
122    if (md == nullptr) {
123        error_ = KM_ERROR_UNSUPPORTED_DIGEST;
124        return;
125    }
126
127    if (purpose == KM_PURPOSE_SIGN) {
128        if (mac_length > EVP_MD_size(md) || mac_length < kMinHmacLengthBits / 8) {
129            error_ = KM_ERROR_UNSUPPORTED_MAC_LENGTH;
130            return;
131        }
132        if (mac_length < min_mac_length) {
133            error_ = KM_ERROR_INVALID_MAC_LENGTH;
134            return;
135        }
136    }
137
138    HMAC_Init_ex(&ctx_, key_data, key_data_size, md, NULL /* engine */);
139}
140
141HmacOperation::~HmacOperation() {
142    HMAC_CTX_cleanup(&ctx_);
143}
144
145keymaster_error_t HmacOperation::Begin(const AuthorizationSet& /* input_params */,
146                                       AuthorizationSet* /* output_params */) {
147    return error_;
148}
149
150keymaster_error_t HmacOperation::Update(const AuthorizationSet& /* additional_params */,
151                                        const Buffer& input, AuthorizationSet* /* output_params */,
152                                        Buffer* /* output */, size_t* input_consumed) {
153    if (!HMAC_Update(&ctx_, input.peek_read(), input.available_read()))
154        return TranslateLastOpenSslError();
155    *input_consumed = input.available_read();
156    return KM_ERROR_OK;
157}
158
159keymaster_error_t HmacOperation::Abort() {
160    return KM_ERROR_OK;
161}
162
163keymaster_error_t HmacOperation::Finish(const AuthorizationSet& /* additional_params */,
164                                        const Buffer& signature,
165                                        AuthorizationSet* /* output_params */, Buffer* output) {
166    uint8_t digest[EVP_MAX_MD_SIZE];
167    unsigned int digest_len;
168    if (!HMAC_Final(&ctx_, digest, &digest_len))
169        return TranslateLastOpenSslError();
170
171    switch (purpose()) {
172    case KM_PURPOSE_SIGN:
173        if (mac_length_ > digest_len)
174            return KM_ERROR_UNSUPPORTED_MAC_LENGTH;
175        if (!output->reserve(mac_length_) || !output->write(digest, mac_length_))
176            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
177        return KM_ERROR_OK;
178    case KM_PURPOSE_VERIFY: {
179        size_t siglen = signature.available_read();
180        if (siglen > digest_len || siglen < kMinHmacLengthBits / 8)
181            return KM_ERROR_UNSUPPORTED_MAC_LENGTH;
182        if (siglen < min_mac_length_)
183            return KM_ERROR_INVALID_MAC_LENGTH;
184        if (CRYPTO_memcmp(signature.peek_read(), digest, siglen) != 0)
185            return KM_ERROR_VERIFICATION_FAILED;
186        return KM_ERROR_OK;
187    }
188    default:
189        return KM_ERROR_UNSUPPORTED_PURPOSE;
190    }
191}
192
193}  // namespace keymaster
194