hmac_operation.cpp revision d79791b0c7123b3fc5db61a0805d7593f19ca8d9
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 <openssl/evp.h>
20#include <openssl/hmac.h>
21
22#include "openssl_err.h"
23#include "symmetric_key.h"
24
25#if defined(OPENSSL_IS_BORINGSSL)
26typedef size_t openssl_size_t;
27#else
28typedef int openssl_size_t;
29#endif
30
31namespace keymaster {
32
33/**
34 * Abstract base for HMAC operation factories.  This class does all of the work to create
35 * HMAC operations.
36 */
37class HmacOperationFactory : public OperationFactory {
38  public:
39    virtual KeyType registry_key() const { return KeyType(KM_ALGORITHM_HMAC, purpose()); }
40
41    virtual Operation* CreateOperation(const Key& key, const AuthorizationSet& begin_params,
42                                       keymaster_error_t* error);
43
44    virtual const keymaster_digest_t* SupportedDigests(size_t* digest_count) const;
45
46    virtual keymaster_purpose_t purpose() const = 0;
47};
48
49Operation* HmacOperationFactory::CreateOperation(const Key& key,
50                                                 const AuthorizationSet& begin_params,
51                                                 keymaster_error_t* error) {
52    uint32_t tag_length = 0;
53    begin_params.GetTagValue(TAG_MAC_LENGTH, &tag_length);
54    if (tag_length % 8 != 0) {
55        LOG_E("MAC length %d nod a multiple of 8 bits", tag_length);
56        *error = KM_ERROR_UNSUPPORTED_MAC_LENGTH;
57        return nullptr;
58    }
59
60    keymaster_digest_t digest = KM_DIGEST_NONE;
61    key.authorizations().GetTagValue(TAG_DIGEST, &digest);
62
63    const SymmetricKey* symmetric_key = static_cast<const SymmetricKey*>(&key);
64    UniquePtr<HmacOperation> op(new HmacOperation(purpose(), symmetric_key->key_data(),
65                                                  symmetric_key->key_data_size(), digest,
66                                                  tag_length / 8));
67    if (!op.get())
68        *error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
69    else
70        *error = op->error();
71
72    if (*error != KM_ERROR_OK)
73        return nullptr;
74
75    return op.release();
76}
77
78static keymaster_digest_t supported_digests[] = {KM_DIGEST_SHA1, KM_DIGEST_SHA_2_224,
79                                                 KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384,
80                                                 KM_DIGEST_SHA_2_512};
81const keymaster_digest_t* HmacOperationFactory::SupportedDigests(size_t* digest_count) const {
82    *digest_count = array_length(supported_digests);
83    return supported_digests;
84}
85
86/**
87 * Concrete factory for creating HMAC signing operations.
88 */
89class HmacSignOperationFactory : public HmacOperationFactory {
90    keymaster_purpose_t purpose() const { return KM_PURPOSE_SIGN; }
91};
92static OperationFactoryRegistry::Registration<HmacSignOperationFactory> sign_registration;
93
94/**
95 * Concrete factory for creating HMAC verification operations.
96 */
97class HmacVerifyOperationFactory : public HmacOperationFactory {
98    keymaster_purpose_t purpose() const { return KM_PURPOSE_VERIFY; }
99};
100static OperationFactoryRegistry::Registration<HmacVerifyOperationFactory> verify_registration;
101
102HmacOperation::HmacOperation(keymaster_purpose_t purpose, const uint8_t* key_data,
103                             size_t key_data_size, keymaster_digest_t digest, size_t tag_length)
104    : Operation(purpose), error_(KM_ERROR_OK), tag_length_(tag_length) {
105    // Initialize CTX first, so dtor won't crash even if we error out later.
106    HMAC_CTX_init(&ctx_);
107
108    const EVP_MD* md = nullptr;
109    switch (digest) {
110    case KM_DIGEST_NONE:
111    case KM_DIGEST_MD5:
112        error_ = KM_ERROR_UNSUPPORTED_DIGEST;
113        break;
114    case KM_DIGEST_SHA1:
115        md = EVP_sha1();
116        break;
117    case KM_DIGEST_SHA_2_224:
118        md = EVP_sha224();
119        break;
120    case KM_DIGEST_SHA_2_256:
121        md = EVP_sha256();
122        break;
123    case KM_DIGEST_SHA_2_384:
124        md = EVP_sha384();
125        break;
126    case KM_DIGEST_SHA_2_512:
127        md = EVP_sha512();
128        break;
129    }
130
131    if (md == nullptr) {
132        error_ = KM_ERROR_UNSUPPORTED_DIGEST;
133        return;
134    }
135
136    HMAC_Init_ex(&ctx_, key_data, key_data_size, md, NULL /* engine */);
137}
138
139HmacOperation::~HmacOperation() {
140    HMAC_CTX_cleanup(&ctx_);
141}
142
143keymaster_error_t HmacOperation::Begin(const AuthorizationSet& /* input_params */,
144                                       AuthorizationSet* /* output_params */) {
145    return error_;
146}
147
148keymaster_error_t HmacOperation::Update(const AuthorizationSet& /* additional_params */,
149                                        const Buffer& input, Buffer* /* output */,
150                                        size_t* input_consumed) {
151    if (!HMAC_Update(&ctx_, input.peek_read(), input.available_read()))
152        return TranslateLastOpenSslError();
153    *input_consumed = input.available_read();
154    return KM_ERROR_OK;
155}
156
157keymaster_error_t HmacOperation::Abort() {
158    return KM_ERROR_OK;
159}
160
161keymaster_error_t HmacOperation::Finish(const AuthorizationSet& /* additional_params */,
162                                        const Buffer& signature, Buffer* output) {
163    uint8_t digest[EVP_MAX_MD_SIZE];
164    unsigned int digest_len;
165    if (!HMAC_Final(&ctx_, digest, &digest_len))
166        return TranslateLastOpenSslError();
167
168    switch (purpose()) {
169    case KM_PURPOSE_SIGN:
170        if (tag_length_ > digest_len)
171            return KM_ERROR_UNSUPPORTED_MAC_LENGTH;
172        if (!output->reserve(tag_length_) || !output->write(digest, tag_length_))
173            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
174        return KM_ERROR_OK;
175    case KM_PURPOSE_VERIFY:
176        if (signature.available_read() > digest_len)
177            return KM_ERROR_INVALID_INPUT_LENGTH;
178        if (CRYPTO_memcmp(signature.peek_read(), digest, signature.available_read()) != 0)
179            return KM_ERROR_VERIFICATION_FAILED;
180        return KM_ERROR_OK;
181    default:
182        return KM_ERROR_UNSUPPORTED_PURPOSE;
183    }
184}
185
186}  // namespace keymaster
187