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