Shawn Willden | 128ffe0 | 2014-08-06 12:31:33 -0600 | [diff] [blame^] | 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 <assert.h> |
| 18 | #include <string.h> |
| 19 | |
| 20 | #include <openssl/rsa.h> |
| 21 | #include <openssl/evp.h> |
| 22 | #include <openssl/err.h> |
| 23 | #include <openssl/sha.h> |
| 24 | |
| 25 | #include <UniquePtr.h> |
| 26 | |
| 27 | #include "google_keymaster.h" |
| 28 | #include "google_keymaster_utils.h" |
| 29 | #include "ae.h" |
| 30 | |
| 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. |
| 33 | inline void* operator new(size_t /* size */, void* here) { return here; } |
| 34 | |
| 35 | namespace keymaster { |
| 36 | |
| 37 | const int NONCE_LENGTH = 12; |
| 38 | const int TAG_LENGTH = 128 / 8; |
| 39 | #define REQUIRED_ALIGNMENT_FOR_AES_OCB 16 |
| 40 | |
| 41 | GoogleKeymaster::GoogleKeymaster() {} |
| 42 | |
| 43 | GoogleKeymaster::~GoogleKeymaster() {} |
| 44 | |
| 45 | const int RSA_DEFAULT_KEY_SIZE = 2048; |
| 46 | const int RSA_DEFAULT_EXPONENT = 65537; |
| 47 | |
| 48 | #define CHECK_ERR(err) \ |
| 49 | if ((err) != OK) \ |
| 50 | return err; |
| 51 | |
| 52 | struct BIGNUM_Delete { |
| 53 | void operator()(BIGNUM* p) const { BN_free(p); } |
| 54 | }; |
| 55 | typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM; |
| 56 | |
| 57 | struct RSA_Delete { |
| 58 | void operator()(RSA* p) const { RSA_free(p); } |
| 59 | }; |
| 60 | typedef UniquePtr<RSA, RSA_Delete> Unique_RSA; |
| 61 | |
| 62 | struct EVP_PKEY_Delete { |
| 63 | void operator()(EVP_PKEY* p) const { EVP_PKEY_free(p); } |
| 64 | }; |
| 65 | typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY; |
| 66 | |
| 67 | struct AE_CTX_Delete { |
| 68 | void operator()(ae_ctx* ctx) const { ae_free(ctx); } |
| 69 | }; |
| 70 | typedef UniquePtr<ae_ctx, AE_CTX_Delete> Unique_ae_ctx; |
| 71 | |
| 72 | struct ByteArray_Delete { |
| 73 | void operator()(void* p) const { delete[] reinterpret_cast<uint8_t*>(p); } |
| 74 | }; |
| 75 | |
| 76 | // Context buffer used for AES OCB encryptions. |
| 77 | uint8_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 | */ |
| 84 | template <typename T, typename Delete_T> |
| 85 | inline void release_because_ownership_transferred(UniquePtr<T, Delete_T>& p) { |
| 86 | T* val __attribute__((unused)) = p.release(); |
| 87 | } |
| 88 | |
| 89 | keymaster_algorithm_t supported_algorithms[] = { |
| 90 | KM_ALGORITHM_RSA, |
| 91 | }; |
| 92 | |
| 93 | template <typename T> |
| 94 | bool 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 | |
| 102 | void |
| 103 | GoogleKeymaster::SupportedAlgorithms(SupportedResponse<keymaster_algorithm_t>* response) const { |
| 104 | if (response == NULL) |
| 105 | return; |
| 106 | response->SetResults(supported_algorithms); |
| 107 | } |
| 108 | |
| 109 | void |
| 110 | GoogleKeymaster::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 | |
| 117 | keymaster_padding_t rsa_supported_padding[] = {KM_PAD_NONE}; |
| 118 | |
| 119 | void |
| 120 | GoogleKeymaster::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 | |
| 136 | keymaster_digest_t rsa_supported_digests[] = {KM_DIGEST_NONE}; |
| 137 | void 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 | |
| 153 | keymaster_key_format_t rsa_supported_import_formats[] = {KM_KEY_FORMAT_PKCS8}; |
| 154 | void |
| 155 | GoogleKeymaster::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 | |
| 171 | keymaster_key_format_t rsa_supported_export_formats[] = {KM_KEY_FORMAT_X509}; |
| 172 | void |
| 173 | GoogleKeymaster::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 | |
| 189 | template <typename Message> |
| 190 | void 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 | |
| 198 | class Eraser { |
| 199 | public: |
| 200 | Eraser(uint8_t* buf, size_t size) : buf_(buf), size_(size) {} |
| 201 | ~Eraser() { |
| 202 | while (size_-- > 0) |
| 203 | *buf_++ = 0; |
| 204 | } |
| 205 | |
| 206 | private: |
| 207 | uint8_t* buf_; |
| 208 | size_t size_; |
| 209 | }; |
| 210 | |
| 211 | void GoogleKeymaster::GenerateKey(const GenerateKeyRequest& request, |
| 212 | GenerateKeyResponse* response) { |
| 213 | if (response == NULL) |
| 214 | return; |
| 215 | response->error = KM_ERROR_OK; |
| 216 | |
| 217 | if (!CopyAuthorizations(request.key_description, response)) |
| 218 | return; |
| 219 | |
| 220 | keymaster_algorithm_t algorithm; |
| 221 | if (!request.key_description.GetTagValue(TAG_ALGORITHM, &algorithm)) { |
| 222 | response->error = KM_ERROR_UNSUPPORTED_ALGORITHM; |
| 223 | return; |
| 224 | } |
| 225 | switch (algorithm) { |
| 226 | case KM_ALGORITHM_RSA: |
| 227 | if (!GenerateRsa(request.key_description, response)) |
| 228 | return; |
| 229 | break; |
| 230 | default: |
| 231 | response->error = KM_ERROR_UNSUPPORTED_ALGORITHM; |
| 232 | return; |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | class KeyBlob { |
| 237 | public: |
| 238 | static KeyBlob* AllocAndInit(GenerateKeyResponse* response, size_t key_len) { |
| 239 | size_t blob_length = get_size(response->enforced, response->unenforced, key_len); |
| 240 | KeyBlob* blob(reinterpret_cast<KeyBlob*>(new uint8_t[blob_length])); |
| 241 | return new (blob) KeyBlob(response->enforced, response->unenforced, key_len); |
| 242 | } |
| 243 | |
| 244 | inline size_t length() { |
| 245 | return get_size(enforced_length(), unenforced_length(), key_length()); |
| 246 | } |
| 247 | inline uint8_t* nonce() { return nonce_; } |
| 248 | inline size_t nonce_length() { return NONCE_LENGTH; } |
| 249 | inline uint8_t* key_data() { return key_data_; } |
| 250 | inline size_t key_length() { return key_length_; } |
| 251 | inline size_t key_data_length() { return key_length_ + TAG_LENGTH; } |
| 252 | inline uint8_t* enforced() { |
| 253 | return key_data_ + key_length_ + TAG_LENGTH + padding(key_length_ + TAG_LENGTH); |
| 254 | } |
| 255 | inline size_t enforced_length() { return enforced_length_; } |
| 256 | inline uint32_t* enforced_length_copy() { |
| 257 | return reinterpret_cast<uint32_t*>(enforced() + enforced_length()); |
| 258 | } |
| 259 | inline uint8_t* unenforced() { return enforced() + enforced_length_ + sizeof(uint32_t); } |
| 260 | inline size_t unenforced_length() { return unenforced_length_; } |
| 261 | inline uint8_t* end() { return unenforced() + unenforced_length_; } |
| 262 | inline uint8_t* auth_data() { return enforced(); } |
| 263 | inline size_t auth_data_length() { return end() - enforced(); } |
| 264 | |
| 265 | private: |
| 266 | KeyBlob(AuthorizationSet& enforced_set, AuthorizationSet& unenforced_set, size_t key_len) |
| 267 | : enforced_length_(enforced_set.SerializedSize()), |
| 268 | unenforced_length_(unenforced_set.SerializedSize()), key_length_(key_len) { |
| 269 | enforced_set.Serialize(enforced()); |
| 270 | unenforced_set.Serialize(unenforced()); |
| 271 | } |
| 272 | |
| 273 | uint32_t enforced_length_; |
| 274 | uint32_t unenforced_length_; |
| 275 | uint32_t key_length_; |
| 276 | uint8_t nonce_[NONCE_LENGTH]; |
| 277 | uint8_t key_data_[] __attribute__((aligned(REQUIRED_ALIGNMENT_FOR_AES_OCB))); |
| 278 | // Actual structure will also include: |
| 279 | // uint8_t enforced[] at key_data + key_length |
| 280 | // uint32_t enforced_length at key_data + key_length + enforced_length |
| 281 | // uint8_t unenforced[] at key_data + key_length + enforced_length. |
| 282 | |
| 283 | static size_t get_size(AuthorizationSet& enforced_set, AuthorizationSet& unenforced_set, |
| 284 | size_t key_len) { |
| 285 | return get_size(enforced_set.SerializedSize(), unenforced_set.SerializedSize(), key_len); |
| 286 | } |
| 287 | |
| 288 | static size_t get_size(size_t enforced_len, size_t unenforced_len, size_t key_len) { |
| 289 | size_t pad_len = padding(key_len + TAG_LENGTH); |
| 290 | return sizeof(KeyBlob) + // includes lengths and nonce |
| 291 | key_len + // key in key_data_ |
| 292 | TAG_LENGTH + // authentication tag in key_data_ |
| 293 | pad_len + // padding to align authorization data |
| 294 | enforced_len + // enforced authorization data |
| 295 | sizeof(uint32_t) + // size of enforced authorization data. This is also in |
| 296 | // enforced_length_ but it's duplicated here to ensure that it's |
| 297 | // included in the OCB-authenticated data, to enforce the |
| 298 | // boundary between enforced and unenforced authorizations. |
| 299 | unenforced_len; // size of unenforced authorization data. |
| 300 | } |
| 301 | |
| 302 | /** |
| 303 | * Return the number of padding bytes needed to round up to the next alignment boundary. |
| 304 | * boundary. |
| 305 | */ |
| 306 | static size_t padding(size_t size) { |
| 307 | return REQUIRED_ALIGNMENT_FOR_AES_OCB - (size % REQUIRED_ALIGNMENT_FOR_AES_OCB); |
| 308 | } |
| 309 | }; |
| 310 | |
| 311 | keymaster_error_t GoogleKeymaster::WrapKey(uint8_t* key_data, size_t key_length, KeyBlob* blob) { |
| 312 | assert(ae_ctx_sizeof() == (int)array_size(aes_ocb_ctx_buf)); |
| 313 | Eraser ctx_eraser(aes_ocb_ctx_buf, array_size(aes_ocb_ctx_buf)); |
| 314 | ae_ctx* ctx = reinterpret_cast<ae_ctx*>(aes_ocb_ctx_buf); |
| 315 | int ae_err = ae_init(ctx, MasterKey(), MasterKeyLength(), blob->nonce_length(), TAG_LENGTH); |
| 316 | if (ae_err != AE_SUCCESS) { |
| 317 | return KM_ERROR_UNKNOWN_ERROR; |
| 318 | } |
| 319 | |
| 320 | GetNonce(blob->nonce(), blob->nonce_length()); |
| 321 | ae_err = ae_encrypt(ctx, blob->nonce(), key_data, key_length, blob->auth_data(), |
| 322 | blob->auth_data_length(), blob->key_data(), NULL, 1 /* final */); |
| 323 | if (ae_err < 0) { |
| 324 | return KM_ERROR_UNKNOWN_ERROR; |
| 325 | } |
| 326 | assert(ae_err == (int)key_length + TAG_LENGTH); |
| 327 | return KM_ERROR_OK; |
| 328 | } |
| 329 | |
| 330 | bool GoogleKeymaster::CreateKeyBlob(GenerateKeyResponse* response, uint8_t* key_bytes, |
| 331 | size_t key_length) { |
| 332 | UniquePtr<KeyBlob, ByteArray_Delete> blob(KeyBlob::AllocAndInit(response, key_length)); |
| 333 | if (blob.get() == NULL) { |
| 334 | response->error = KM_ERROR_MEMORY_ALLOCATION_FAILED; |
| 335 | return false; |
| 336 | } |
| 337 | |
| 338 | keymaster_error_t err = WrapKey(key_bytes, key_length, blob.get()); |
| 339 | if (err != KM_ERROR_OK) { |
| 340 | response->error = err; |
| 341 | return false; |
| 342 | } |
| 343 | |
| 344 | response->key_blob.key_material_size = blob->length(); |
| 345 | response->key_blob.key_material = reinterpret_cast<uint8_t*>(blob.release()); |
| 346 | |
| 347 | return true; |
| 348 | } |
| 349 | |
| 350 | bool GoogleKeymaster::GenerateRsa(const AuthorizationSet& key_auths, |
| 351 | GenerateKeyResponse* response) { |
| 352 | uint64_t public_exponent = RSA_DEFAULT_EXPONENT; |
| 353 | if (!key_auths.GetTagValue(TAG_RSA_PUBLIC_EXPONENT, &public_exponent)) |
| 354 | AddAuthorization(Authorization(TAG_RSA_PUBLIC_EXPONENT, public_exponent), response); |
| 355 | |
| 356 | uint32_t key_size = RSA_DEFAULT_KEY_SIZE; |
| 357 | if (!key_auths.GetTagValue(TAG_KEY_SIZE, &key_size)) |
| 358 | AddAuthorization(Authorization(TAG_KEY_SIZE, key_size), response); |
| 359 | |
| 360 | Unique_BIGNUM exponent(BN_new()); |
| 361 | Unique_RSA rsa_key(RSA_new()); |
| 362 | Unique_EVP_PKEY pkey(EVP_PKEY_new()); |
| 363 | if (rsa_key.get() == NULL || pkey.get() == NULL) { |
| 364 | response->error = KM_ERROR_MEMORY_ALLOCATION_FAILED; |
| 365 | return false; |
| 366 | } |
| 367 | |
| 368 | if (!BN_set_word(exponent.get(), public_exponent) || |
| 369 | !RSA_generate_key_ex(rsa_key.get(), key_size, exponent.get(), NULL /* callback */)) { |
| 370 | response->error = KM_ERROR_UNKNOWN_ERROR; |
| 371 | return false; |
| 372 | } |
| 373 | |
| 374 | if (!EVP_PKEY_assign_RSA(pkey.get(), rsa_key.get())) { |
| 375 | response->error = KM_ERROR_UNKNOWN_ERROR; |
| 376 | return false; |
| 377 | } else { |
| 378 | release_because_ownership_transferred(rsa_key); |
| 379 | } |
| 380 | |
| 381 | int der_length = i2d_PrivateKey(pkey.get(), NULL); |
| 382 | if (der_length <= 0) { |
| 383 | response->error = KM_ERROR_UNKNOWN_ERROR; |
| 384 | return false; |
| 385 | } |
| 386 | UniquePtr<uint8_t[]> der_data(new uint8_t[der_length]); |
| 387 | if (der_data.get() == NULL) { |
| 388 | response->error = KM_ERROR_MEMORY_ALLOCATION_FAILED; |
| 389 | return false; |
| 390 | } |
| 391 | |
| 392 | uint8_t* tmp = der_data.get(); |
| 393 | i2d_PrivateKey(pkey.get(), &tmp); |
| 394 | |
| 395 | return CreateKeyBlob(response, der_data.get(), der_length); |
| 396 | } |
| 397 | |
| 398 | static keymaster_error_t CheckAuthorizationSet(const AuthorizationSet& set) { |
| 399 | switch (set.is_valid()) { |
| 400 | case AuthorizationSet::OK_FULL: |
| 401 | case AuthorizationSet::OK_GROWABLE: |
| 402 | return KM_ERROR_OK; |
| 403 | case AuthorizationSet::ALLOCATION_FAILURE: |
| 404 | return KM_ERROR_MEMORY_ALLOCATION_FAILED; |
| 405 | case AuthorizationSet::BOUNDS_CHECKING_FAILURE: |
| 406 | case AuthorizationSet::MALFORMED_DATA: |
| 407 | return KM_ERROR_UNKNOWN_ERROR; |
| 408 | } |
| 409 | return KM_ERROR_OK; |
| 410 | } |
| 411 | |
| 412 | bool GoogleKeymaster::CopyAuthorizations(const AuthorizationSet& key_description, |
| 413 | GenerateKeyResponse* response) { |
| 414 | for (size_t i = 0; i < key_description.size(); ++i) { |
| 415 | switch (key_description[i].tag) { |
| 416 | case KM_TAG_ROOT_OF_TRUST: |
| 417 | case KM_TAG_CREATION_DATETIME: |
| 418 | case KM_TAG_ORIGIN: |
| 419 | response->error = KM_ERROR_INVALID_TAG; |
| 420 | return false; |
| 421 | case KM_TAG_ROLLBACK_RESISTANT: |
| 422 | response->error = KM_ERROR_UNSUPPORTED_TAG; |
| 423 | return false; |
| 424 | default: |
| 425 | AddAuthorization(key_description[i], response); |
| 426 | break; |
| 427 | } |
| 428 | } |
| 429 | |
| 430 | AddAuthorization(Authorization(TAG_CREATION_DATETIME, java_time(time(NULL))), response); |
| 431 | AddAuthorization(Authorization(TAG_ORIGIN, origin()), response); |
| 432 | AddAuthorization(Authorization(TAG_ROOT_OF_TRUST, "SW", 2), response); |
| 433 | |
| 434 | response->error = CheckAuthorizationSet(response->enforced); |
| 435 | if (response->error != KM_ERROR_OK) |
| 436 | return false; |
| 437 | response->error = CheckAuthorizationSet(response->unenforced); |
| 438 | if (response->error != KM_ERROR_OK) |
| 439 | return false; |
| 440 | |
| 441 | return true; |
| 442 | } |
| 443 | |
| 444 | void GoogleKeymaster::AddAuthorization(const keymaster_key_param_t& auth, |
| 445 | GenerateKeyResponse* response) { |
| 446 | if (is_enforced(auth.tag)) |
| 447 | response->enforced.push_back(auth); |
| 448 | else |
| 449 | response->unenforced.push_back(auth); |
| 450 | } |
| 451 | |
| 452 | } // namespace keymaster |