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 <keymaster/km_openssl/hmac_key.h>
23 #include <keymaster/km_openssl/openssl_err.h>
24 #include <keymaster/km_openssl/openssl_utils.h>
25 
26 #if defined(OPENSSL_IS_BORINGSSL)
27 #include <openssl/mem.h>
28 typedef size_t openssl_size_t;
29 #else
30 typedef int openssl_size_t;
31 #endif
32 
33 namespace keymaster {
34 
CreateOperation(Key && key,const AuthorizationSet & begin_params,keymaster_error_t * error)35 OperationPtr HmacOperationFactory::CreateOperation(Key&& key, const AuthorizationSet& begin_params,
36                                                    keymaster_error_t* error) {
37     uint32_t min_mac_length_bits;
38     if (!key.authorizations().GetTagValue(TAG_MIN_MAC_LENGTH, &min_mac_length_bits)) {
39         LOG_E("HMAC key must have KM_TAG_MIN_MAC_LENGTH", 0);
40         *error = KM_ERROR_INVALID_KEY_BLOB;
41         return nullptr;
42     }
43 
44     uint32_t mac_length_bits = UINT32_MAX;
45     if (begin_params.GetTagValue(TAG_MAC_LENGTH, &mac_length_bits)) {
46         if (purpose() == KM_PURPOSE_VERIFY) {
47             LOG_E("MAC length may not be specified for verify", 0);
48             *error = KM_ERROR_INVALID_ARGUMENT;
49             return nullptr;
50         }
51         if ((mac_length_bits % 8) != 0) {
52             LOG_E("MAC length must be a multiple of 8", mac_length_bits);
53             *error = KM_ERROR_UNSUPPORTED_MAC_LENGTH;
54             return nullptr;
55         }
56     } else {
57         if (purpose() == KM_PURPOSE_SIGN) {
58             *error = KM_ERROR_MISSING_MAC_LENGTH;
59             return nullptr;
60         }
61     }
62 
63     keymaster_digest_t digest;
64     if (!key.authorizations().GetTagValue(TAG_DIGEST, &digest)) {
65         LOG_E("%d digests found in HMAC key authorizations; must be exactly 1",
66               begin_params.GetTagCount(TAG_DIGEST));
67         *error = KM_ERROR_INVALID_KEY_BLOB;
68         return nullptr;
69     }
70 
71     UniquePtr<HmacOperation> op(new (std::nothrow) HmacOperation(
72         move(key), purpose(), digest, mac_length_bits / 8, min_mac_length_bits / 8));
73     if (!op.get())
74         *error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
75     else
76         *error = op->error();
77 
78     if (*error != KM_ERROR_OK) return nullptr;
79 
80     return move(op);
81 }
82 
83 static 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};
SupportedDigests(size_t * digest_count) const86 const keymaster_digest_t* HmacOperationFactory::SupportedDigests(size_t* digest_count) const {
87     *digest_count = array_length(supported_digests);
88     return supported_digests;
89 }
90 
HmacOperation(Key && key,keymaster_purpose_t purpose,keymaster_digest_t digest,size_t mac_length,size_t min_mac_length)91 HmacOperation::HmacOperation(Key&& key, keymaster_purpose_t purpose, keymaster_digest_t digest,
92                              size_t mac_length, size_t min_mac_length)
93     : Operation(purpose, key.hw_enforced_move(), key.sw_enforced_move()), error_(KM_ERROR_OK),
94       mac_length_(mac_length), min_mac_length_(min_mac_length) {
95     // Initialize CTX first, so dtor won't crash even if we error out later.
96     HMAC_CTX_init(&ctx_);
97 
98     const EVP_MD* md = nullptr;
99     switch (digest) {
100     case KM_DIGEST_NONE:
101     case KM_DIGEST_MD5:
102         error_ = KM_ERROR_UNSUPPORTED_DIGEST;
103         break;
104     case KM_DIGEST_SHA1:
105         md = EVP_sha1();
106         break;
107     case KM_DIGEST_SHA_2_224:
108         md = EVP_sha224();
109         break;
110     case KM_DIGEST_SHA_2_256:
111         md = EVP_sha256();
112         break;
113     case KM_DIGEST_SHA_2_384:
114         md = EVP_sha384();
115         break;
116     case KM_DIGEST_SHA_2_512:
117         md = EVP_sha512();
118         break;
119     }
120 
121     if (md == nullptr) {
122         error_ = KM_ERROR_UNSUPPORTED_DIGEST;
123         return;
124     }
125 
126     if (purpose == KM_PURPOSE_SIGN) {
127         if (mac_length > EVP_MD_size(md) || mac_length < kMinHmacLengthBits / 8) {
128             error_ = KM_ERROR_UNSUPPORTED_MAC_LENGTH;
129             return;
130         }
131         if (mac_length < min_mac_length) {
132             error_ = KM_ERROR_INVALID_MAC_LENGTH;
133             return;
134         }
135     }
136 
137     KeymasterKeyBlob blob = key.key_material_move();
138     HMAC_Init_ex(&ctx_, blob.key_material, blob.key_material_size, md, nullptr /* engine */);
139 }
140 
~HmacOperation()141 HmacOperation::~HmacOperation() {
142     HMAC_CTX_cleanup(&ctx_);
143 }
144 
Begin(const AuthorizationSet &,AuthorizationSet *)145 keymaster_error_t HmacOperation::Begin(const AuthorizationSet& /* input_params */,
146                                        AuthorizationSet* /* output_params */) {
147     auto rc = GenerateRandom(reinterpret_cast<uint8_t*>(&operation_handle_),
148                              (size_t)sizeof(operation_handle_));
149     if (rc != KM_ERROR_OK) return rc;
150 
151     return error_;
152 }
153 
Update(const AuthorizationSet &,const Buffer & input,AuthorizationSet *,Buffer *,size_t * input_consumed)154 keymaster_error_t HmacOperation::Update(const AuthorizationSet& /* additional_params */,
155                                         const Buffer& input, AuthorizationSet* /* output_params */,
156                                         Buffer* /* output */, size_t* input_consumed) {
157     if (!HMAC_Update(&ctx_, input.peek_read(), input.available_read()))
158         return TranslateLastOpenSslError();
159     *input_consumed = input.available_read();
160     return KM_ERROR_OK;
161 }
162 
Abort()163 keymaster_error_t HmacOperation::Abort() {
164     return KM_ERROR_OK;
165 }
166 
Finish(const AuthorizationSet & additional_params,const Buffer & input,const Buffer & signature,AuthorizationSet *,Buffer * output)167 keymaster_error_t HmacOperation::Finish(const AuthorizationSet& additional_params,
168                                         const Buffer& input, const Buffer& signature,
169                                         AuthorizationSet* /* output_params */, Buffer* output) {
170     keymaster_error_t error = UpdateForFinish(additional_params, input);
171     if (error != KM_ERROR_OK) return error;
172 
173     uint8_t digest[EVP_MAX_MD_SIZE];
174     unsigned int digest_len;
175     if (!HMAC_Final(&ctx_, digest, &digest_len)) return TranslateLastOpenSslError();
176 
177     switch (purpose()) {
178     case KM_PURPOSE_SIGN:
179         if (mac_length_ > digest_len) return KM_ERROR_UNSUPPORTED_MAC_LENGTH;
180         if (!output->reserve(mac_length_) || !output->write(digest, mac_length_))
181             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
182         return KM_ERROR_OK;
183     case KM_PURPOSE_VERIFY: {
184         size_t siglen = signature.available_read();
185         if (siglen > digest_len || siglen < kMinHmacLengthBits / 8)
186             return KM_ERROR_UNSUPPORTED_MAC_LENGTH;
187         if (siglen < min_mac_length_) return KM_ERROR_INVALID_MAC_LENGTH;
188         if (CRYPTO_memcmp(signature.peek_read(), digest, siglen) != 0)
189             return KM_ERROR_VERIFICATION_FAILED;
190         return KM_ERROR_OK;
191     }
192     default:
193         return KM_ERROR_UNSUPPORTED_PURPOSE;
194     }
195 }
196 
197 }  // namespace keymaster
198