1 /* 2 ** 3 ** Copyright 2017, The Android Open Source Project 4 ** 5 ** Licensed under the Apache License, Version 2.0 (the "License"); 6 ** you may not use this file except in compliance with the License. 7 ** You may obtain a copy of the License at 8 ** 9 ** http://www.apache.org/licenses/LICENSE-2.0 10 ** 11 ** Unless required by applicable law or agreed to in writing, software 12 ** distributed under the License is distributed on an "AS IS" BASIS, 13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 ** See the License for the specific language governing permissions and 15 ** limitations under the License. 16 */ 17 18 #include <keymaster/km_openssl/attestation_utils.h> 19 20 #include <hardware/keymaster_defs.h> 21 22 #include <keymaster/authorization_set.h> 23 #include <keymaster/attestation_record.h> 24 #include <keymaster/km_openssl/asymmetric_key.h> 25 #include <keymaster/km_openssl/openssl_utils.h> 26 #include <keymaster/km_openssl/openssl_err.h> 27 28 #include <openssl/x509v3.h> 29 #include <openssl/evp.h> 30 31 32 namespace keymaster { 33 34 namespace { 35 36 constexpr int kDigitalSignatureKeyUsageBit = 0; 37 constexpr int kKeyEnciphermentKeyUsageBit = 2; 38 constexpr int kDataEnciphermentKeyUsageBit = 3; 39 constexpr int kMaxKeyUsageBit = 8; 40 41 template <typename T> T && min(T && a, T && b) { 42 return (a < b) ? forward<T>(a) : forward<T>(b); 43 } 44 45 struct emptyCert {}; 46 47 __attribute__((__unused__)) 48 inline keymaster_blob_t certBlobifier(const emptyCert&, bool*){ return {}; } 49 template <size_t N> 50 inline keymaster_blob_t certBlobifier(const uint8_t (&cert)[N], bool* fail){ 51 keymaster_blob_t result = { dup_array(cert), N }; 52 if (!result.data) { 53 *fail = true; 54 return {}; 55 } 56 return result; 57 } 58 inline keymaster_blob_t certBlobifier(const keymaster_blob_t& blob, bool* fail){ 59 if (blob.data == nullptr || blob.data_length == 0) return {}; 60 keymaster_blob_t result = { dup_array(blob.data, blob.data_length), blob.data_length }; 61 if (!result.data) { 62 *fail = true; 63 return {}; 64 } 65 return result; 66 } 67 inline keymaster_blob_t certBlobifier(keymaster_blob_t&& blob, bool*){ 68 if (blob.data == nullptr || blob.data_length == 0) return {}; 69 keymaster_blob_t result = blob; 70 blob = {}; 71 return result; 72 } 73 inline keymaster_blob_t certBlobifier(X509* certificate, bool* fail){ 74 int len = i2d_X509(certificate, nullptr); 75 if (len < 0) { 76 *fail = true; 77 return {}; 78 } 79 80 uint8_t* data = new(std::nothrow) uint8_t[len]; 81 if (!data) { 82 *fail = true; 83 return {}; 84 } 85 uint8_t* p = data; 86 87 i2d_X509(certificate, &p); 88 89 return { data, (size_t)len }; 90 } 91 92 inline bool certCopier(keymaster_blob_t** out, const keymaster_cert_chain_t& chain, 93 bool* fail) { 94 for (size_t i = 0; i < chain.entry_count; ++i) { 95 *(*out)++ = certBlobifier(chain.entries[i], fail); 96 } 97 return *fail; 98 } 99 100 __attribute__((__unused__)) 101 inline bool certCopier(keymaster_blob_t** out, keymaster_cert_chain_t&& chain, bool* fail) { 102 for (size_t i = 0; i < chain.entry_count; ++i) { 103 *(*out)++ = certBlobifier(move(chain.entries[i]), fail); 104 } 105 delete[] chain.entries; 106 chain.entries = nullptr; 107 chain.entry_count = 0; 108 return *fail; 109 } 110 template <typename CERT> 111 inline bool certCopier(keymaster_blob_t** out, CERT&& cert, bool* fail) { 112 *(*out)++ = certBlobifier(forward<CERT>(cert), fail); 113 return *fail; 114 } 115 116 inline bool certCopyHelper(keymaster_blob_t**, bool* fail) { 117 return *fail; 118 } 119 120 template <typename CERT, typename... CERTS> 121 inline bool certCopyHelper(keymaster_blob_t** out, bool* fail, CERT&& cert, CERTS&&... certs) { 122 certCopier(out, forward<CERT>(cert), fail); 123 return certCopyHelper(out, fail, forward<CERTS>(certs)...); 124 } 125 126 127 128 template <typename T> 129 inline size_t noOfCert(T &&) { return 1; } 130 inline size_t noOfCert(const keymaster_cert_chain_t& cert_chain) { return cert_chain.entry_count; } 131 132 inline size_t certCount() { return 0; } 133 template <typename CERT, typename... CERTS> 134 inline size_t certCount(CERT&& cert, CERTS&&... certs) { 135 return noOfCert(forward<CERT>(cert)) + certCount(forward<CERTS>(certs)...); 136 } 137 138 /* 139 * makeCertChain creates a new keymaster_cert_chain_t from all the certs that get thrown at it 140 * in the given order. A cert may be a X509*, uint8_t[], a keymaster_blob_t, an instance of 141 * emptyCert, or another keymater_cert_chain_t in which case the certs of the chain are included 142 * in the new chain. emptyCert is a placeholder which results in an empty slot at the given 143 * position in the newly created certificate chain. E.g., makeCertChain(emptyCert(), someCertChain) 144 * allocates enough slots to accommodate all certificates of someCertChain plus one empty slot and 145 * copies in someCertChain starting at index 1 so that the slot with index 0 can be used for a new 146 * leaf entry. 147 * 148 * makeCertChain respects move semantics. E.g., makeCertChain(emptyCert(), std::move(someCertChain)) 149 * will take possession of secondary resources for the certificate blobs so that someCertChain is 150 * empty after the call. Also, because no allocation happens this cannot fail. Note, however, that 151 * if another cert is passed to makeCertChain, that needs to be copied and thus requires 152 * allocation, and this allocation fails, all resources - allocated or moved - will be reaped. 153 */ 154 template <typename... CERTS> 155 CertChainPtr makeCertChain(CERTS&&... certs) { 156 CertChainPtr result(new (std::nothrow) keymaster_cert_chain_t); 157 if (!result.get()) return {}; 158 result->entries = new (std::nothrow) keymaster_blob_t[certCount(forward<CERTS>(certs)...)]; 159 if (!result->entries) return {}; 160 result->entry_count = certCount(forward<CERTS>(certs)...); 161 bool allocation_failed = false; 162 keymaster_blob_t* entries = result->entries; 163 certCopyHelper(&entries, &allocation_failed, forward<CERTS>(certs)...); 164 if (allocation_failed) return {}; 165 return result; 166 } 167 168 keymaster_error_t build_attestation_extension(const AuthorizationSet& attest_params, 169 const AuthorizationSet& tee_enforced, 170 const AuthorizationSet& sw_enforced, 171 const uint keymaster_version, 172 const AttestationRecordContext& context, 173 X509_EXTENSION_Ptr* extension) { 174 ASN1_OBJECT_Ptr oid( 175 OBJ_txt2obj(kAttestionRecordOid, 1 /* accept numerical dotted string form only */)); 176 if (!oid.get()) 177 return TranslateLastOpenSslError(); 178 179 UniquePtr<uint8_t[]> attest_bytes; 180 size_t attest_bytes_len; 181 keymaster_error_t error = 182 build_attestation_record(attest_params, sw_enforced, tee_enforced, context, 183 keymaster_version, &attest_bytes, &attest_bytes_len); 184 if (error != KM_ERROR_OK) 185 return error; 186 187 ASN1_OCTET_STRING_Ptr attest_str(ASN1_OCTET_STRING_new()); 188 if (!attest_str.get() || 189 !ASN1_OCTET_STRING_set(attest_str.get(), attest_bytes.get(), attest_bytes_len)) 190 return TranslateLastOpenSslError(); 191 192 extension->reset( 193 X509_EXTENSION_create_by_OBJ(nullptr, oid.get(), 0 /* not critical */, attest_str.get())); 194 if (!extension->get()) 195 return TranslateLastOpenSslError(); 196 197 return KM_ERROR_OK; 198 } 199 200 keymaster_error_t add_key_usage_extension(const AuthorizationSet& tee_enforced, 201 const AuthorizationSet& sw_enforced, 202 X509* certificate) { 203 // Build BIT_STRING with correct contents. 204 ASN1_BIT_STRING_Ptr key_usage(ASN1_BIT_STRING_new()); 205 if (!key_usage) return KM_ERROR_MEMORY_ALLOCATION_FAILED; 206 207 for (size_t i = 0; i <= kMaxKeyUsageBit; ++i) { 208 if (!ASN1_BIT_STRING_set_bit(key_usage.get(), i, 0)) { 209 return TranslateLastOpenSslError(); 210 } 211 } 212 213 if (tee_enforced.Contains(TAG_PURPOSE, KM_PURPOSE_SIGN) || 214 tee_enforced.Contains(TAG_PURPOSE, KM_PURPOSE_VERIFY) || 215 sw_enforced.Contains(TAG_PURPOSE, KM_PURPOSE_SIGN) || 216 sw_enforced.Contains(TAG_PURPOSE, KM_PURPOSE_VERIFY)) { 217 if (!ASN1_BIT_STRING_set_bit(key_usage.get(), kDigitalSignatureKeyUsageBit, 1)) { 218 return TranslateLastOpenSslError(); 219 } 220 } 221 222 if (tee_enforced.Contains(TAG_PURPOSE, KM_PURPOSE_ENCRYPT) || 223 tee_enforced.Contains(TAG_PURPOSE, KM_PURPOSE_DECRYPT) || 224 sw_enforced.Contains(TAG_PURPOSE, KM_PURPOSE_ENCRYPT) || 225 sw_enforced.Contains(TAG_PURPOSE, KM_PURPOSE_DECRYPT)) { 226 if (!ASN1_BIT_STRING_set_bit(key_usage.get(), kKeyEnciphermentKeyUsageBit, 1) || 227 !ASN1_BIT_STRING_set_bit(key_usage.get(), kDataEnciphermentKeyUsageBit, 1)) { 228 return TranslateLastOpenSslError(); 229 } 230 } 231 232 // Convert to octets 233 int len = i2d_ASN1_BIT_STRING(key_usage.get(), nullptr); 234 if (len < 0) { 235 return TranslateLastOpenSslError(); 236 } 237 UniquePtr<uint8_t[]> asn1_key_usage(new(std::nothrow) uint8_t[len]); 238 if (!asn1_key_usage.get()) { 239 return KM_ERROR_MEMORY_ALLOCATION_FAILED; 240 } 241 uint8_t* p = asn1_key_usage.get(); 242 len = i2d_ASN1_BIT_STRING(key_usage.get(), &p); 243 if (len < 0) { 244 return TranslateLastOpenSslError(); 245 } 246 247 // Build OCTET_STRING 248 ASN1_OCTET_STRING_Ptr key_usage_str(ASN1_OCTET_STRING_new()); 249 if (!key_usage_str.get() || 250 !ASN1_OCTET_STRING_set(key_usage_str.get(), asn1_key_usage.get(), len)) { 251 return TranslateLastOpenSslError(); 252 } 253 254 X509_EXTENSION_Ptr key_usage_extension(X509_EXTENSION_create_by_NID(nullptr, // 255 NID_key_usage, // 256 false /* critical */, 257 key_usage_str.get())); 258 if (!key_usage_extension.get()) { 259 return TranslateLastOpenSslError(); 260 } 261 262 if (!X509_add_ext(certificate, key_usage_extension.get() /* Don't release; copied */, 263 -1 /* insert at end */)) { 264 return TranslateLastOpenSslError(); 265 } 266 267 return KM_ERROR_OK; 268 } 269 270 bool add_public_key(const EVP_PKEY* key, X509* certificate, keymaster_error_t* error) { 271 if (!X509_set_pubkey(certificate, (EVP_PKEY*)key)) { 272 *error = TranslateLastOpenSslError(); 273 return false; 274 } 275 return true; 276 } 277 278 bool add_attestation_extension(const AuthorizationSet& attest_params, 279 const AuthorizationSet& tee_enforced, 280 const AuthorizationSet& sw_enforced, 281 const AttestationRecordContext& context, 282 const uint keymaster_version, X509* certificate, 283 keymaster_error_t* error) { 284 X509_EXTENSION_Ptr attest_extension; 285 *error = build_attestation_extension(attest_params, tee_enforced, sw_enforced, 286 keymaster_version, context, &attest_extension); 287 if (*error != KM_ERROR_OK) 288 return false; 289 290 if (!X509_add_ext(certificate, attest_extension.get() /* Don't release; copied */, 291 -1 /* insert at end */)) { 292 *error = TranslateLastOpenSslError(); 293 return false; 294 } 295 296 return true; 297 } 298 299 } // anonymous namespace 300 301 keymaster_error_t generate_attestation_common( 302 const EVP_PKEY* evp_key, // input 303 const AuthorizationSet& sw_enforced, // input 304 const AuthorizationSet& hw_enforced, // input 305 const AuthorizationSet& attest_params, // input. Sub function require app id to be set here. 306 uint64_t 307 activeDateTimeMilliSeconds, // input, certificate active time in milliseconds since epoch 308 uint64_t usageExpireDateTimeMilliSeconds, // Input, certificate expire time in milliseconds 309 // since epoch 310 const uint keymaster_version, 311 const AttestationRecordContext& context, // input 312 const keymaster_cert_chain_t& attestation_chain, // input 313 const keymaster_key_blob_t& attestation_signing_key, // input 314 CertChainPtr* cert_chain_out) { // Output. 315 316 if (!cert_chain_out) { 317 return KM_ERROR_UNEXPECTED_NULL_POINTER; 318 } 319 320 X509_Ptr certificate(X509_new()); 321 if (!certificate.get()) { 322 return TranslateLastOpenSslError(); 323 } 324 325 if (!X509_set_version(certificate.get(), 2 /* version 3, but zero-based */)) 326 return TranslateLastOpenSslError(); 327 328 ASN1_INTEGER_Ptr serialNumber(ASN1_INTEGER_new()); 329 if (!serialNumber.get() || !ASN1_INTEGER_set(serialNumber.get(), 1) || 330 !X509_set_serialNumber(certificate.get(), serialNumber.get() /* Don't release; copied */)) 331 return TranslateLastOpenSslError(); 332 333 X509_NAME_Ptr subjectName(X509_NAME_new()); 334 if (!subjectName.get() || 335 !X509_NAME_add_entry_by_txt(subjectName.get(), // 336 "CN", // 337 MBSTRING_ASC, 338 reinterpret_cast<const uint8_t*>("Android Keystore Key"), 339 -1, // len 340 -1, // loc 341 0 /* set */) || 342 !X509_set_subject_name(certificate.get(), subjectName.get() /* Don't release; copied */)) 343 return TranslateLastOpenSslError(); 344 345 ASN1_TIME_Ptr notBefore(ASN1_TIME_new()); 346 347 if (!notBefore.get() || !ASN1_TIME_set(notBefore.get(), activeDateTimeMilliSeconds / 1000) || 348 !X509_set_notBefore(certificate.get(), notBefore.get() /* Don't release; copied */)) 349 return TranslateLastOpenSslError(); 350 351 ASN1_TIME_Ptr notAfter(ASN1_TIME_new()); 352 353 // TODO(swillden): When trusty can use the C++ standard library change the calculation of 354 // notAfterTime to use std::numeric_limits<time_t>::max(), rather than assuming that time_t 355 // is 32 bits. 356 time_t notAfterTime; 357 notAfterTime = 358 (time_t)min(static_cast<uint64_t>(UINT32_MAX), usageExpireDateTimeMilliSeconds / 1000); 359 360 if (!notAfter.get() || !ASN1_TIME_set(notAfter.get(), notAfterTime) || 361 !X509_set_notAfter(certificate.get(), notAfter.get() /* Don't release; copied */)) 362 return TranslateLastOpenSslError(); 363 364 keymaster_error_t error = add_key_usage_extension(hw_enforced, sw_enforced, certificate.get()); 365 if (error != KM_ERROR_OK) { 366 return error; 367 } 368 369 int evp_key_type = EVP_PKEY_type(evp_key->type); 370 371 const uint8_t* key_material = attestation_signing_key.key_material; 372 EVP_PKEY_Ptr sign_key(d2i_PrivateKey(evp_key_type, nullptr, &key_material, 373 attestation_signing_key.key_material_size)); 374 375 if (!sign_key.get()) { 376 return TranslateLastOpenSslError(); 377 } 378 379 if (!add_public_key(evp_key, certificate.get(), &error) || 380 !add_attestation_extension(attest_params, hw_enforced, sw_enforced, context, 381 keymaster_version, certificate.get(), &error)) 382 return error; 383 384 if (attestation_chain.entry_count < 1) { 385 // the attestation chain must have at least the cert for the key that signs the new 386 // cert. 387 return KM_ERROR_UNKNOWN_ERROR; 388 } 389 390 const uint8_t* p = attestation_chain.entries[0].data; 391 X509_Ptr signing_cert(d2i_X509(nullptr, &p, attestation_chain.entries[0].data_length)); 392 if (!signing_cert.get()) { 393 return TranslateLastOpenSslError(); 394 } 395 396 // Set issuer to subject of batch certificate. 397 X509_NAME* issuerSubject = X509_get_subject_name(signing_cert.get()); 398 if (!issuerSubject) { 399 return KM_ERROR_UNKNOWN_ERROR; 400 } 401 402 if (!X509_set_issuer_name(certificate.get(), issuerSubject)) { 403 return TranslateLastOpenSslError(); 404 } 405 406 UniquePtr<X509V3_CTX> x509v3_ctx(new (std::nothrow) X509V3_CTX); 407 if (!x509v3_ctx.get()) { 408 return KM_ERROR_MEMORY_ALLOCATION_FAILED; 409 } 410 411 *x509v3_ctx = {}; 412 X509V3_set_ctx(x509v3_ctx.get(), // 413 signing_cert.get(), // signing certificate 414 certificate.get(), // 415 nullptr, // req 416 nullptr, // crl 417 0 /* flags */); 418 419 X509_EXTENSION_Ptr auth_key_id(X509V3_EXT_nconf_nid(nullptr, // conf 420 x509v3_ctx.get(), // 421 NID_authority_key_identifier, 422 const_cast<char*>("keyid:always"))); 423 if (!auth_key_id.get() || !X509_add_ext(certificate.get(), // 424 auth_key_id.get(), // Don't release; copied 425 -1 /* insert at end */)) { 426 return TranslateLastOpenSslError(); 427 } 428 429 if (!X509_sign(certificate.get(), sign_key.get(), EVP_sha256())) 430 return TranslateLastOpenSslError(); 431 432 if (attest_params.Contains(TAG_DEVICE_UNIQUE_ATTESTATION)) { 433 // When we're pretending to be a StrongBox doing device-unique attestation, we don't chain 434 // back to anything, but just return the plain certificate. 435 *cert_chain_out = makeCertChain(certificate.get()); 436 } else { 437 *cert_chain_out = makeCertChain(certificate.get(), attestation_chain); 438 } 439 if (!cert_chain_out->get()) return KM_ERROR_MEMORY_ALLOCATION_FAILED; 440 return KM_ERROR_OK; 441 } 442 443 // Generate attestation certificate base on the AsymmetricKey key and other parameters 444 // passed in. In attest_params, we expects the challenge, active time and expiration 445 // time, and app id. 446 // 447 // The active time and expiration time are expected in milliseconds. 448 // 449 // Hardware and software enforced AuthorizationSet are expected to be built into the AsymmetricKey 450 // input. In hardware enforced AuthorizationSet, we expects hardware related tags such as 451 // TAG_IDENTITY_CREDENTIAL_KEY. 452 keymaster_error_t generate_attestation(const AsymmetricKey& key, 453 const AuthorizationSet& attest_params, 454 const keymaster_cert_chain_t& attestation_chain, 455 const keymaster_key_blob_t& attestation_signing_key, 456 const AttestationRecordContext& context, 457 CertChainPtr* cert_chain_out) { 458 459 // assume the conversion to EVP key correctly encodes the key type such 460 // that EVP_PKEY_type(evp_key->type) returns correctly. 461 EVP_PKEY_Ptr pkey(EVP_PKEY_new()); 462 if (!key.InternalToEvp(pkey.get())) { 463 return TranslateLastOpenSslError(); 464 } 465 466 uint64_t activeDateTime = 0; 467 key.authorizations().GetTagValue(TAG_ACTIVE_DATETIME, &activeDateTime); 468 469 uint64_t usageExpireDateTime = UINT64_MAX; 470 key.authorizations().GetTagValue(TAG_USAGE_EXPIRE_DATETIME, &usageExpireDateTime); 471 472 return generate_attestation_common(pkey.get(), key.sw_enforced(), key.hw_enforced(), 473 attest_params, activeDateTime, usageExpireDateTime, 474 kCurrentKeymasterVersion, context, attestation_chain, 475 attestation_signing_key, cert_chain_out); 476 } 477 478 // Generate attestation certificate base on the EVP key and other parameters 479 // passed in. Note that due to sub sub sub function call setup, there are 3 AuthorizationSet 480 // passed in, hardware, software, and attest_params. In attest_params, we expects the 481 // challenge, active time and expiration time, and app id. In hw_enforced, we expects 482 // hardware related tags such as TAG_IDENTITY_CREDENTIAL_KEY. 483 // 484 // The active time and expiration time are expected in milliseconds. 485 keymaster_error_t generate_attestation_from_EVP( 486 const EVP_PKEY* evp_key, // input 487 const AuthorizationSet& sw_enforced, // input 488 const AuthorizationSet& hw_enforced, // input 489 const AuthorizationSet& attest_params, // input. Sub function require app id to be set here. 490 const AttestationRecordContext& context, // input 491 const uint keymaster_version, // input 492 const keymaster_cert_chain_t& attestation_chain, // input 493 const keymaster_key_blob_t& attestation_signing_key, // input 494 CertChainPtr* cert_chain_out) { // Output. 495 496 uint64_t activeDateTime = 0; 497 attest_params.GetTagValue(TAG_ACTIVE_DATETIME, &activeDateTime); 498 499 uint64_t usageExpireDateTime = UINT64_MAX; 500 attest_params.GetTagValue(TAG_USAGE_EXPIRE_DATETIME, &usageExpireDateTime); 501 502 return generate_attestation_common( 503 evp_key, sw_enforced, hw_enforced, attest_params, activeDateTime, usageExpireDateTime, 504 keymaster_version, context, attestation_chain, attestation_signing_key, cert_chain_out); 505 } 506 507 } // namespace keymaster 508