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 <keymaster/new.h>
20 
21 #include <openssl/evp.h>
22 #include <openssl/hmac.h>
23 
24 #include <keymaster/km_openssl/hmac_key.h>
25 #include <keymaster/km_openssl/openssl_err.h>
26 #include <keymaster/km_openssl/openssl_utils.h>
27 
28 #if defined(OPENSSL_IS_BORINGSSL)
29 #include <openssl/mem.h>
30 typedef size_t openssl_size_t;
31 #else
32 typedef int openssl_size_t;
33 #endif
34 
35 namespace keymaster {
36 
37 OperationPtr HmacOperationFactory::CreateOperation(Key&& key, 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     UniquePtr<HmacOperation> op(new (std::nothrow) HmacOperation(
69         move(key), purpose(), digest, mac_length_bits / 8, min_mac_length_bits / 8));
70     if (!op.get())
71         *error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
72     else
73         *error = op->error();
74 
75     if (*error != KM_ERROR_OK) return nullptr;
76 
77     return move(op);
78 }
79 
80 static keymaster_digest_t supported_digests[] = {KM_DIGEST_SHA1, KM_DIGEST_SHA_2_224,
81                                                  KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384,
82                                                  KM_DIGEST_SHA_2_512};
83 const keymaster_digest_t* HmacOperationFactory::SupportedDigests(size_t* digest_count) const {
84     *digest_count = array_length(supported_digests);
85     return supported_digests;
86 }
87 
88 HmacOperation::HmacOperation(Key&& key, keymaster_purpose_t purpose, keymaster_digest_t digest,
89                              size_t mac_length, size_t min_mac_length)
90     : Operation(purpose, key.hw_enforced_move(), key.sw_enforced_move()), error_(KM_ERROR_OK),
91       mac_length_(mac_length), min_mac_length_(min_mac_length) {
92     // Initialize CTX first, so dtor won't crash even if we error out later.
93     HMAC_CTX_init(&ctx_);
94 
95     const EVP_MD* md = nullptr;
96     switch (digest) {
97     case KM_DIGEST_NONE:
98     case KM_DIGEST_MD5:
99         error_ = KM_ERROR_UNSUPPORTED_DIGEST;
100         break;
101     case KM_DIGEST_SHA1:
102         md = EVP_sha1();
103         break;
104     case KM_DIGEST_SHA_2_224:
105         md = EVP_sha224();
106         break;
107     case KM_DIGEST_SHA_2_256:
108         md = EVP_sha256();
109         break;
110     case KM_DIGEST_SHA_2_384:
111         md = EVP_sha384();
112         break;
113     case KM_DIGEST_SHA_2_512:
114         md = EVP_sha512();
115         break;
116     }
117 
118     if (md == nullptr) {
119         error_ = KM_ERROR_UNSUPPORTED_DIGEST;
120         return;
121     }
122 
123     if (purpose == KM_PURPOSE_SIGN) {
124         if (mac_length > EVP_MD_size(md) || mac_length < kMinHmacLengthBits / 8) {
125             error_ = KM_ERROR_UNSUPPORTED_MAC_LENGTH;
126             return;
127         }
128         if (mac_length < min_mac_length) {
129             error_ = KM_ERROR_INVALID_MAC_LENGTH;
130             return;
131         }
132     }
133 
134     KeymasterKeyBlob blob = key.key_material_move();
135     HMAC_Init_ex(&ctx_, blob.key_material, blob.key_material_size, md, nullptr /* engine */);
136 }
137 
138 HmacOperation::~HmacOperation() {
139     HMAC_CTX_cleanup(&ctx_);
140 }
141 
142 keymaster_error_t HmacOperation::Begin(const AuthorizationSet& /* input_params */,
143                                        AuthorizationSet* /* output_params */) {
144     auto rc = GenerateRandom(reinterpret_cast<uint8_t*>(&operation_handle_),
145                              (size_t)sizeof(operation_handle_));
146     if (rc != KM_ERROR_OK) return rc;
147 
148     return error_;
149 }
150 
151 keymaster_error_t HmacOperation::Update(const AuthorizationSet& /* additional_params */,
152                                         const Buffer& input, AuthorizationSet* /* output_params */,
153                                         Buffer* /* output */, size_t* input_consumed) {
154     if (!HMAC_Update(&ctx_, input.peek_read(), input.available_read()))
155         return TranslateLastOpenSslError();
156     *input_consumed = input.available_read();
157     return KM_ERROR_OK;
158 }
159 
160 keymaster_error_t HmacOperation::Abort() {
161     return KM_ERROR_OK;
162 }
163 
164 keymaster_error_t HmacOperation::Finish(const AuthorizationSet& additional_params,
165                                         const Buffer& input, const Buffer& signature,
166                                         AuthorizationSet* /* output_params */, Buffer* output) {
167     keymaster_error_t error = UpdateForFinish(additional_params, input);
168     if (error != KM_ERROR_OK) return error;
169 
170     uint8_t digest[EVP_MAX_MD_SIZE];
171     unsigned int digest_len;
172     if (!HMAC_Final(&ctx_, digest, &digest_len)) return TranslateLastOpenSslError();
173 
174     switch (purpose()) {
175     case KM_PURPOSE_SIGN:
176         if (mac_length_ > digest_len) return KM_ERROR_UNSUPPORTED_MAC_LENGTH;
177         if (!output->reserve(mac_length_) || !output->write(digest, mac_length_))
178             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
179         return KM_ERROR_OK;
180     case KM_PURPOSE_VERIFY: {
181         size_t siglen = signature.available_read();
182         if (siglen > digest_len || siglen < kMinHmacLengthBits / 8)
183             return KM_ERROR_UNSUPPORTED_MAC_LENGTH;
184         if (siglen < min_mac_length_) return KM_ERROR_INVALID_MAC_LENGTH;
185         if (CRYPTO_memcmp(signature.peek_read(), digest, siglen) != 0)
186             return KM_ERROR_VERIFICATION_FAILED;
187         return KM_ERROR_OK;
188     }
189     default:
190         return KM_ERROR_UNSUPPORTED_PURPOSE;
191     }
192 }
193 
194 }  // namespace keymaster
195