blob: acfc1ee54066fe6d268b7260edd0ab9c4577bcb6 [file] [log] [blame]
Shawn Willden128ffe02014-08-06 12:31:33 -06001/*
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 <assert.h>
18#include <string.h>
19
Shawn Willden128ffe02014-08-06 12:31:33 -060020#include <openssl/err.h>
Shawn Willden3879f862014-08-06 14:40:48 -060021#include <openssl/evp.h>
22#include <openssl/rsa.h>
Shawn Willden128ffe02014-08-06 12:31:33 -060023#include <openssl/sha.h>
24
25#include <UniquePtr.h>
26
Shawn Willden3879f862014-08-06 14:40:48 -060027#include "ae.h"
Shawn Willden128ffe02014-08-06 12:31:33 -060028#include "google_keymaster.h"
29#include "google_keymaster_utils.h"
Shawn Willden128ffe02014-08-06 12:31:33 -060030
31// We need placement new, but we don't want to pull in any standard C++ libs at the moment.
32// Luckily, it's trivial to just implement it.
33inline void* operator new(size_t /* size */, void* here) { return here; }
34
35namespace keymaster {
36
37const int NONCE_LENGTH = 12;
38const int TAG_LENGTH = 128 / 8;
39#define REQUIRED_ALIGNMENT_FOR_AES_OCB 16
40
41GoogleKeymaster::GoogleKeymaster() {}
42
43GoogleKeymaster::~GoogleKeymaster() {}
44
45const int RSA_DEFAULT_KEY_SIZE = 2048;
46const int RSA_DEFAULT_EXPONENT = 65537;
47
48#define CHECK_ERR(err) \
49 if ((err) != OK) \
50 return err;
51
52struct BIGNUM_Delete {
53 void operator()(BIGNUM* p) const { BN_free(p); }
54};
55typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
56
57struct RSA_Delete {
58 void operator()(RSA* p) const { RSA_free(p); }
59};
60typedef UniquePtr<RSA, RSA_Delete> Unique_RSA;
61
62struct EVP_PKEY_Delete {
63 void operator()(EVP_PKEY* p) const { EVP_PKEY_free(p); }
64};
65typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
66
67struct AE_CTX_Delete {
68 void operator()(ae_ctx* ctx) const { ae_free(ctx); }
69};
70typedef UniquePtr<ae_ctx, AE_CTX_Delete> Unique_ae_ctx;
71
72struct ByteArray_Delete {
73 void operator()(void* p) const { delete[] reinterpret_cast<uint8_t*>(p); }
74};
75
76// Context buffer used for AES OCB encryptions.
77uint8_t aes_ocb_ctx_buf[896];
78
79/**
80 * Many OpenSSL APIs take ownership of an argument on success but don't free the argument on
81 * failure. This means we need to tell our scoped pointers when we've transferred ownership, without
82 * triggering a warning by not using the result of release().
83 */
84template <typename T, typename Delete_T>
85inline void release_because_ownership_transferred(UniquePtr<T, Delete_T>& p) {
86 T* val __attribute__((unused)) = p.release();
87}
88
89keymaster_algorithm_t supported_algorithms[] = {
90 KM_ALGORITHM_RSA,
91};
92
93template <typename T>
94bool check_supported(keymaster_algorithm_t algorithm, SupportedResponse<T>* response) {
95 if (!array_contains(supported_algorithms, algorithm)) {
96 response->error = KM_ERROR_UNSUPPORTED_ALGORITHM;
97 return false;
98 }
99 return true;
100}
101
102void
103GoogleKeymaster::SupportedAlgorithms(SupportedResponse<keymaster_algorithm_t>* response) const {
104 if (response == NULL)
105 return;
106 response->SetResults(supported_algorithms);
107}
108
109void
110GoogleKeymaster::SupportedBlockModes(keymaster_algorithm_t algorithm,
111 SupportedResponse<keymaster_block_mode_t>* response) const {
112 if (response == NULL || !check_supported(algorithm, response))
113 return;
114 response->error = KM_ERROR_OK;
115}
116
117keymaster_padding_t rsa_supported_padding[] = {KM_PAD_NONE};
118
119void
120GoogleKeymaster::SupportedPaddingModes(keymaster_algorithm_t algorithm,
121 SupportedResponse<keymaster_padding_t>* response) const {
122 if (response == NULL || !check_supported(algorithm, response))
123 return;
124
125 response->error = KM_ERROR_OK;
126 switch (algorithm) {
127 case KM_ALGORITHM_RSA:
128 response->SetResults(rsa_supported_padding);
129 break;
130 default:
131 response->results_length = 0;
132 break;
133 }
134}
135
136keymaster_digest_t rsa_supported_digests[] = {KM_DIGEST_NONE};
137void GoogleKeymaster::SupportedDigests(keymaster_algorithm_t algorithm,
138 SupportedResponse<keymaster_digest_t>* response) const {
139 if (response == NULL || !check_supported(algorithm, response))
140 return;
141
142 response->error = KM_ERROR_OK;
143 switch (algorithm) {
144 case KM_ALGORITHM_RSA:
145 response->SetResults(rsa_supported_digests);
146 break;
147 default:
148 response->results_length = 0;
149 break;
150 }
151}
152
153keymaster_key_format_t rsa_supported_import_formats[] = {KM_KEY_FORMAT_PKCS8};
154void
155GoogleKeymaster::SupportedImportFormats(keymaster_algorithm_t algorithm,
156 SupportedResponse<keymaster_key_format_t>* response) const {
157 if (response == NULL || !check_supported(algorithm, response))
158 return;
159
160 response->error = KM_ERROR_OK;
161 switch (algorithm) {
162 case KM_ALGORITHM_RSA:
163 response->SetResults(rsa_supported_import_formats);
164 break;
165 default:
166 response->results_length = 0;
167 break;
168 }
169}
170
171keymaster_key_format_t rsa_supported_export_formats[] = {KM_KEY_FORMAT_X509};
172void
173GoogleKeymaster::SupportedExportFormats(keymaster_algorithm_t algorithm,
174 SupportedResponse<keymaster_key_format_t>* response) const {
175 if (response == NULL || !check_supported(algorithm, response))
176 return;
177
178 response->error = KM_ERROR_OK;
179 switch (algorithm) {
180 case KM_ALGORITHM_RSA:
181 response->SetResults(rsa_supported_export_formats);
182 break;
183 default:
184 response->results_length = 0;
185 break;
186 }
187}
188
189template <typename Message>
190void store_bignum(Message* message, void (Message::*set)(const void* value, size_t size),
191 BIGNUM* bignum) {
192 size_t bufsize = BN_num_bytes(bignum);
193 UniquePtr<uint8_t[]> buf(new uint8_t[bufsize]);
194 int bytes_written = BN_bn2bin(bignum, buf.get());
195 (message->*set)(buf.get(), bytes_written);
196}
197
Shawn Willden128ffe02014-08-06 12:31:33 -0600198void GoogleKeymaster::GenerateKey(const GenerateKeyRequest& request,
199 GenerateKeyResponse* response) {
200 if (response == NULL)
201 return;
202 response->error = KM_ERROR_OK;
203
204 if (!CopyAuthorizations(request.key_description, response))
205 return;
206
207 keymaster_algorithm_t algorithm;
208 if (!request.key_description.GetTagValue(TAG_ALGORITHM, &algorithm)) {
209 response->error = KM_ERROR_UNSUPPORTED_ALGORITHM;
210 return;
211 }
212 switch (algorithm) {
213 case KM_ALGORITHM_RSA:
214 if (!GenerateRsa(request.key_description, response))
215 return;
216 break;
217 default:
218 response->error = KM_ERROR_UNSUPPORTED_ALGORITHM;
219 return;
220 }
221}
222
223class KeyBlob {
224 public:
225 static KeyBlob* AllocAndInit(GenerateKeyResponse* response, size_t key_len) {
226 size_t blob_length = get_size(response->enforced, response->unenforced, key_len);
227 KeyBlob* blob(reinterpret_cast<KeyBlob*>(new uint8_t[blob_length]));
228 return new (blob) KeyBlob(response->enforced, response->unenforced, key_len);
229 }
230
231 inline size_t length() {
232 return get_size(enforced_length(), unenforced_length(), key_length());
233 }
234 inline uint8_t* nonce() { return nonce_; }
235 inline size_t nonce_length() { return NONCE_LENGTH; }
236 inline uint8_t* key_data() { return key_data_; }
237 inline size_t key_length() { return key_length_; }
238 inline size_t key_data_length() { return key_length_ + TAG_LENGTH; }
239 inline uint8_t* enforced() {
240 return key_data_ + key_length_ + TAG_LENGTH + padding(key_length_ + TAG_LENGTH);
241 }
242 inline size_t enforced_length() { return enforced_length_; }
243 inline uint32_t* enforced_length_copy() {
244 return reinterpret_cast<uint32_t*>(enforced() + enforced_length());
245 }
246 inline uint8_t* unenforced() { return enforced() + enforced_length_ + sizeof(uint32_t); }
247 inline size_t unenforced_length() { return unenforced_length_; }
248 inline uint8_t* end() { return unenforced() + unenforced_length_; }
249 inline uint8_t* auth_data() { return enforced(); }
250 inline size_t auth_data_length() { return end() - enforced(); }
251
252 private:
253 KeyBlob(AuthorizationSet& enforced_set, AuthorizationSet& unenforced_set, size_t key_len)
254 : enforced_length_(enforced_set.SerializedSize()),
255 unenforced_length_(unenforced_set.SerializedSize()), key_length_(key_len) {
Shawn Willden58e1a542014-08-08 21:58:29 -0600256 enforced_set.Serialize(enforced(), enforced() + enforced_length());
257 unenforced_set.Serialize(unenforced(), unenforced() + unenforced_length());
Shawn Willden128ffe02014-08-06 12:31:33 -0600258 }
259
260 uint32_t enforced_length_;
261 uint32_t unenforced_length_;
262 uint32_t key_length_;
263 uint8_t nonce_[NONCE_LENGTH];
264 uint8_t key_data_[] __attribute__((aligned(REQUIRED_ALIGNMENT_FOR_AES_OCB)));
265 // Actual structure will also include:
266 // uint8_t enforced[] at key_data + key_length
267 // uint32_t enforced_length at key_data + key_length + enforced_length
268 // uint8_t unenforced[] at key_data + key_length + enforced_length.
269
270 static size_t get_size(AuthorizationSet& enforced_set, AuthorizationSet& unenforced_set,
271 size_t key_len) {
272 return get_size(enforced_set.SerializedSize(), unenforced_set.SerializedSize(), key_len);
273 }
274
275 static size_t get_size(size_t enforced_len, size_t unenforced_len, size_t key_len) {
276 size_t pad_len = padding(key_len + TAG_LENGTH);
277 return sizeof(KeyBlob) + // includes lengths and nonce
278 key_len + // key in key_data_
279 TAG_LENGTH + // authentication tag in key_data_
280 pad_len + // padding to align authorization data
281 enforced_len + // enforced authorization data
282 sizeof(uint32_t) + // size of enforced authorization data. This is also in
283 // enforced_length_ but it's duplicated here to ensure that it's
284 // included in the OCB-authenticated data, to enforce the
285 // boundary between enforced and unenforced authorizations.
286 unenforced_len; // size of unenforced authorization data.
287 }
288
289 /**
290 * Return the number of padding bytes needed to round up to the next alignment boundary.
291 * boundary.
292 */
293 static size_t padding(size_t size) {
294 return REQUIRED_ALIGNMENT_FOR_AES_OCB - (size % REQUIRED_ALIGNMENT_FOR_AES_OCB);
295 }
296};
297
298keymaster_error_t GoogleKeymaster::WrapKey(uint8_t* key_data, size_t key_length, KeyBlob* blob) {
299 assert(ae_ctx_sizeof() == (int)array_size(aes_ocb_ctx_buf));
300 Eraser ctx_eraser(aes_ocb_ctx_buf, array_size(aes_ocb_ctx_buf));
301 ae_ctx* ctx = reinterpret_cast<ae_ctx*>(aes_ocb_ctx_buf);
302 int ae_err = ae_init(ctx, MasterKey(), MasterKeyLength(), blob->nonce_length(), TAG_LENGTH);
303 if (ae_err != AE_SUCCESS) {
304 return KM_ERROR_UNKNOWN_ERROR;
305 }
306
307 GetNonce(blob->nonce(), blob->nonce_length());
308 ae_err = ae_encrypt(ctx, blob->nonce(), key_data, key_length, blob->auth_data(),
309 blob->auth_data_length(), blob->key_data(), NULL, 1 /* final */);
310 if (ae_err < 0) {
311 return KM_ERROR_UNKNOWN_ERROR;
312 }
313 assert(ae_err == (int)key_length + TAG_LENGTH);
314 return KM_ERROR_OK;
315}
316
317bool GoogleKeymaster::CreateKeyBlob(GenerateKeyResponse* response, uint8_t* key_bytes,
318 size_t key_length) {
319 UniquePtr<KeyBlob, ByteArray_Delete> blob(KeyBlob::AllocAndInit(response, key_length));
320 if (blob.get() == NULL) {
321 response->error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
322 return false;
323 }
324
325 keymaster_error_t err = WrapKey(key_bytes, key_length, blob.get());
326 if (err != KM_ERROR_OK) {
327 response->error = err;
328 return false;
329 }
330
331 response->key_blob.key_material_size = blob->length();
332 response->key_blob.key_material = reinterpret_cast<uint8_t*>(blob.release());
333
334 return true;
335}
336
337bool GoogleKeymaster::GenerateRsa(const AuthorizationSet& key_auths,
338 GenerateKeyResponse* response) {
339 uint64_t public_exponent = RSA_DEFAULT_EXPONENT;
340 if (!key_auths.GetTagValue(TAG_RSA_PUBLIC_EXPONENT, &public_exponent))
341 AddAuthorization(Authorization(TAG_RSA_PUBLIC_EXPONENT, public_exponent), response);
342
343 uint32_t key_size = RSA_DEFAULT_KEY_SIZE;
344 if (!key_auths.GetTagValue(TAG_KEY_SIZE, &key_size))
345 AddAuthorization(Authorization(TAG_KEY_SIZE, key_size), response);
346
347 Unique_BIGNUM exponent(BN_new());
348 Unique_RSA rsa_key(RSA_new());
349 Unique_EVP_PKEY pkey(EVP_PKEY_new());
350 if (rsa_key.get() == NULL || pkey.get() == NULL) {
351 response->error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
352 return false;
353 }
354
355 if (!BN_set_word(exponent.get(), public_exponent) ||
356 !RSA_generate_key_ex(rsa_key.get(), key_size, exponent.get(), NULL /* callback */)) {
357 response->error = KM_ERROR_UNKNOWN_ERROR;
358 return false;
359 }
360
361 if (!EVP_PKEY_assign_RSA(pkey.get(), rsa_key.get())) {
362 response->error = KM_ERROR_UNKNOWN_ERROR;
363 return false;
364 } else {
365 release_because_ownership_transferred(rsa_key);
366 }
367
368 int der_length = i2d_PrivateKey(pkey.get(), NULL);
369 if (der_length <= 0) {
370 response->error = KM_ERROR_UNKNOWN_ERROR;
371 return false;
372 }
373 UniquePtr<uint8_t[]> der_data(new uint8_t[der_length]);
374 if (der_data.get() == NULL) {
375 response->error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
376 return false;
377 }
378
379 uint8_t* tmp = der_data.get();
380 i2d_PrivateKey(pkey.get(), &tmp);
381
382 return CreateKeyBlob(response, der_data.get(), der_length);
383}
384
385static keymaster_error_t CheckAuthorizationSet(const AuthorizationSet& set) {
386 switch (set.is_valid()) {
Shawn Willden58e1a542014-08-08 21:58:29 -0600387 case AuthorizationSet::OK:
Shawn Willden128ffe02014-08-06 12:31:33 -0600388 return KM_ERROR_OK;
389 case AuthorizationSet::ALLOCATION_FAILURE:
390 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
391 case AuthorizationSet::BOUNDS_CHECKING_FAILURE:
392 case AuthorizationSet::MALFORMED_DATA:
393 return KM_ERROR_UNKNOWN_ERROR;
394 }
395 return KM_ERROR_OK;
396}
397
398bool GoogleKeymaster::CopyAuthorizations(const AuthorizationSet& key_description,
399 GenerateKeyResponse* response) {
400 for (size_t i = 0; i < key_description.size(); ++i) {
401 switch (key_description[i].tag) {
402 case KM_TAG_ROOT_OF_TRUST:
403 case KM_TAG_CREATION_DATETIME:
404 case KM_TAG_ORIGIN:
405 response->error = KM_ERROR_INVALID_TAG;
406 return false;
407 case KM_TAG_ROLLBACK_RESISTANT:
408 response->error = KM_ERROR_UNSUPPORTED_TAG;
409 return false;
410 default:
411 AddAuthorization(key_description[i], response);
412 break;
413 }
414 }
415
416 AddAuthorization(Authorization(TAG_CREATION_DATETIME, java_time(time(NULL))), response);
417 AddAuthorization(Authorization(TAG_ORIGIN, origin()), response);
418 AddAuthorization(Authorization(TAG_ROOT_OF_TRUST, "SW", 2), response);
419
420 response->error = CheckAuthorizationSet(response->enforced);
421 if (response->error != KM_ERROR_OK)
422 return false;
423 response->error = CheckAuthorizationSet(response->unenforced);
424 if (response->error != KM_ERROR_OK)
425 return false;
426
427 return true;
428}
429
430void GoogleKeymaster::AddAuthorization(const keymaster_key_param_t& auth,
431 GenerateKeyResponse* response) {
432 if (is_enforced(auth.tag))
433 response->enforced.push_back(auth);
434 else
435 response->unenforced.push_back(auth);
436}
437
438} // namespace keymaster