1 /* 2 * Copyright 2020, 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 <openssl/asn1.h> 18 #include <openssl/evp.h> 19 #include <openssl/x509v3.h> 20 21 #include <hardware/keymaster_defs.h> 22 #include <keymaster/android_keymaster_utils.h> 23 #include <keymaster/authorization_set.h> 24 #include <keymaster/km_openssl/asymmetric_key.h> 25 #include <keymaster/km_openssl/certificate_utils.h> 26 #include <keymaster/km_openssl/openssl_err.h> 27 #include <keymaster/logger.h> 28 29 namespace keymaster { 30 31 namespace { 32 33 constexpr const char kDefaultSubject[] = "Android Keystore Key"; 34 constexpr int kDataEnciphermentKeyUsageBit = 3; 35 constexpr int kDigitalSignatureKeyUsageBit = 0; 36 constexpr int kKeyEnciphermentKeyUsageBit = 2; 37 constexpr int kKeyAgreementKeyUsageBit = 4; 38 constexpr int kMaxKeyUsageBit = 8; 39 40 template <typename T> T&& min(T&& a, T&& b) { 41 return (a < b) ? forward<T>(a) : forward<T>(b); 42 } 43 44 keymaster_error_t fake_sign_cert(X509* cert) { 45 // Set algorithm in TBSCertificate 46 X509_ALGOR_set0(cert->cert_info->signature, OBJ_nid2obj(NID_sha256WithRSAEncryption), 47 V_ASN1_NULL, nullptr); 48 49 // Set algorithm in Certificate 50 X509_ALGOR_set0(cert->sig_alg, OBJ_nid2obj(NID_sha256WithRSAEncryption), V_ASN1_NULL, nullptr); 51 52 // Set signature to a bit string containing a single byte, value 0. 53 uint8_t fake_sig = 0; 54 if (!cert->signature) cert->signature = ASN1_BIT_STRING_new(); 55 if (!cert->signature) return KM_ERROR_MEMORY_ALLOCATION_FAILED; 56 if (!ASN1_STRING_set(cert->signature, &fake_sig, sizeof(fake_sig))) { 57 return TranslateLastOpenSslError(); 58 } 59 60 return KM_ERROR_OK; 61 } 62 63 } // namespace 64 65 keymaster_error_t make_name_from_str(const char name[], X509_NAME_Ptr* name_out) { 66 if (name_out == nullptr) return KM_ERROR_UNEXPECTED_NULL_POINTER; 67 X509_NAME_Ptr x509_name(X509_NAME_new()); 68 if (!x509_name.get()) { 69 return TranslateLastOpenSslError(); 70 } 71 if (!X509_NAME_add_entry_by_txt(x509_name.get(), // 72 "CN", // 73 MBSTRING_ASC, reinterpret_cast<const uint8_t*>(&name[0]), 74 -1, // len 75 -1, // loc 76 0 /* set */)) { 77 return TranslateLastOpenSslError(); 78 } 79 *name_out = move(x509_name); 80 return KM_ERROR_OK; 81 } 82 83 keymaster_error_t make_name_from_der(const keymaster_blob_t& name, X509_NAME_Ptr* name_out) { 84 if (!name_out || !name.data) return KM_ERROR_UNEXPECTED_NULL_POINTER; 85 86 const uint8_t* p = name.data; 87 X509_NAME_Ptr x509_name(d2i_X509_NAME(nullptr, &p, name.data_length)); 88 if (!x509_name.get()) { 89 return TranslateLastOpenSslError(); 90 } 91 92 *name_out = move(x509_name); 93 return KM_ERROR_OK; 94 } 95 96 keymaster_error_t get_common_name(X509_NAME* name, UniquePtr<const char[]>* name_out) { 97 if (name == nullptr || name_out == nullptr) return KM_ERROR_UNEXPECTED_NULL_POINTER; 98 int len = X509_NAME_get_text_by_NID(name, NID_commonName, nullptr, 0); 99 UniquePtr<char[]> name_ptr(new (std::nothrow) char[len]); 100 if (!name_ptr) { 101 return KM_ERROR_MEMORY_ALLOCATION_FAILED; 102 } 103 X509_NAME_get_text_by_NID(name, NID_commonName, name_ptr.get(), len); 104 *name_out = UniquePtr<const char[]>{name_ptr.release()}; 105 return KM_ERROR_OK; 106 } 107 108 keymaster_error_t get_certificate_params(const AuthorizationSet& caller_params, 109 CertificateCallerParams* cert_params, 110 KmVersion kmVersion) { 111 if (!cert_params) return KM_ERROR_UNEXPECTED_NULL_POINTER; 112 113 BIGNUM_Ptr serial(BN_new()); 114 if (!serial) { 115 return KM_ERROR_MEMORY_ALLOCATION_FAILED; 116 } 117 118 keymaster_blob_t serial_blob{.data = nullptr, .data_length = 0}; 119 if (caller_params.GetTagValue(TAG_CERTIFICATE_SERIAL, &serial_blob)) { 120 if (BN_bin2bn(serial_blob.data, serial_blob.data_length, serial.get()) == nullptr) { 121 return TranslateLastOpenSslError(); 122 } 123 } else { 124 // Default serial is one. 125 BN_one(serial.get()); 126 } 127 cert_params->serial = move(serial); 128 129 cert_params->active_date_time = 0; 130 cert_params->expire_date_time = kUndefinedExpirationDateTime; 131 132 uint64_t tmp; 133 switch (kmVersion) { 134 case KmVersion::KEYMASTER_1: 135 case KmVersion::KEYMASTER_1_1: 136 case KmVersion::KEYMASTER_2: 137 case KmVersion::KEYMASTER_3: 138 case KmVersion::KEYMASTER_4: 139 case KmVersion::KEYMASTER_4_1: 140 if (caller_params.GetTagValue(TAG_ACTIVE_DATETIME, &tmp)) { 141 LOG_D("Using TAG_ACTIVE_DATETIME: %lu", tmp); 142 cert_params->active_date_time = static_cast<int64_t>(tmp); 143 } 144 if (caller_params.GetTagValue(TAG_ORIGINATION_EXPIRE_DATETIME, &tmp)) { 145 LOG_D("Using TAG_ORIGINATION_EXPIRE_DATETIME: %lu", tmp); 146 cert_params->expire_date_time = static_cast<int64_t>(tmp); 147 } 148 break; 149 150 case KmVersion::KEYMINT_1: 151 if (!caller_params.GetTagValue(TAG_CERTIFICATE_NOT_BEFORE, &tmp)) { 152 return KM_ERROR_MISSING_NOT_BEFORE; 153 } 154 LOG_D("Using TAG_CERTIFICATE_NOT_BEFORE: %lu", tmp); 155 cert_params->active_date_time = static_cast<int64_t>(tmp); 156 157 if (!caller_params.GetTagValue(TAG_CERTIFICATE_NOT_AFTER, &tmp)) { 158 return KM_ERROR_MISSING_NOT_AFTER; 159 } 160 LOG_D("Using TAG_CERTIFICATE_NOT_AFTER: %lu", tmp); 161 cert_params->expire_date_time = static_cast<int64_t>(tmp); 162 } 163 164 LOG_D("Got certificate date params: NotBefore = %ld, NotAfter = %ld", 165 cert_params->active_date_time, cert_params->expire_date_time); 166 167 keymaster_blob_t subject{}; 168 if (caller_params.GetTagValue(TAG_CERTIFICATE_SUBJECT, &subject) && subject.data_length) { 169 return make_name_from_der(subject, &cert_params->subject_name); 170 } 171 172 return make_name_from_str(kDefaultSubject, &cert_params->subject_name); 173 } 174 175 keymaster_error_t make_key_usage_extension(bool is_signing_key, bool is_encryption_key, 176 bool is_key_agreement_key, 177 X509_EXTENSION_Ptr* usage_extension_out) { 178 if (usage_extension_out == nullptr) return KM_ERROR_UNEXPECTED_NULL_POINTER; 179 180 // Build BIT_STRING with correct contents. 181 ASN1_BIT_STRING_Ptr key_usage(ASN1_BIT_STRING_new()); 182 if (!key_usage) return KM_ERROR_MEMORY_ALLOCATION_FAILED; 183 184 for (size_t i = 0; i <= kMaxKeyUsageBit; ++i) { 185 if (!ASN1_BIT_STRING_set_bit(key_usage.get(), i, 0)) { 186 return TranslateLastOpenSslError(); 187 } 188 } 189 190 if (is_signing_key) { 191 if (!ASN1_BIT_STRING_set_bit(key_usage.get(), kDigitalSignatureKeyUsageBit, 1)) { 192 return TranslateLastOpenSslError(); 193 } 194 } 195 196 if (is_encryption_key) { 197 if (!ASN1_BIT_STRING_set_bit(key_usage.get(), kKeyEnciphermentKeyUsageBit, 1) || 198 !ASN1_BIT_STRING_set_bit(key_usage.get(), kDataEnciphermentKeyUsageBit, 1)) { 199 return TranslateLastOpenSslError(); 200 } 201 } 202 203 if (is_key_agreement_key) { 204 if (!ASN1_BIT_STRING_set_bit(key_usage.get(), kKeyAgreementKeyUsageBit, 1)) { 205 return TranslateLastOpenSslError(); 206 } 207 } 208 209 // Convert to octets 210 int len = i2d_ASN1_BIT_STRING(key_usage.get(), nullptr); 211 if (len < 0) { 212 return TranslateLastOpenSslError(); 213 } 214 UniquePtr<uint8_t[]> asn1_key_usage(new (std::nothrow) uint8_t[len]); 215 if (!asn1_key_usage.get()) { 216 return KM_ERROR_MEMORY_ALLOCATION_FAILED; 217 } 218 uint8_t* p = asn1_key_usage.get(); 219 len = i2d_ASN1_BIT_STRING(key_usage.get(), &p); 220 if (len < 0) { 221 return TranslateLastOpenSslError(); 222 } 223 224 // Build OCTET_STRING 225 ASN1_OCTET_STRING_Ptr key_usage_str(ASN1_OCTET_STRING_new()); 226 if (!key_usage_str.get() || 227 !ASN1_OCTET_STRING_set(key_usage_str.get(), asn1_key_usage.get(), len)) { 228 return TranslateLastOpenSslError(); 229 } 230 231 X509_EXTENSION_Ptr key_usage_extension(X509_EXTENSION_create_by_NID(nullptr, // 232 NID_key_usage, // 233 true /* critical */, 234 key_usage_str.get())); 235 if (!key_usage_extension.get()) { 236 return TranslateLastOpenSslError(); 237 } 238 239 *usage_extension_out = move(key_usage_extension); 240 241 return KM_ERROR_OK; 242 } 243 244 // Creates a rump certificate structure with serial, subject and issuer names, as well as 245 // activation and expiry date. 246 // Callers should pass an empty X509_Ptr and check the return value for KM_ERROR_OK (0) before 247 // accessing the result. 248 keymaster_error_t make_cert_rump(const X509_NAME* issuer, 249 const CertificateCallerParams& cert_params, X509_Ptr* cert_out) { 250 if (!cert_out || !issuer) return KM_ERROR_UNEXPECTED_NULL_POINTER; 251 252 // Create certificate structure. 253 X509_Ptr certificate(X509_new()); 254 if (!certificate.get()) return TranslateLastOpenSslError(); 255 256 // Set the X509 version. 257 if (!X509_set_version(certificate.get(), 2 /* version 3 */)) return TranslateLastOpenSslError(); 258 259 // Set the certificate serialNumber 260 ASN1_INTEGER_Ptr serial_number(ASN1_INTEGER_new()); 261 if (!serial_number.get() || // 262 !BN_to_ASN1_INTEGER(cert_params.serial.get(), serial_number.get()) || 263 !X509_set_serialNumber(certificate.get(), 264 serial_number.get() /* Don't release; copied */)) { 265 return TranslateLastOpenSslError(); 266 } 267 268 if (!X509_set_subject_name(certificate.get(), 269 const_cast<X509_NAME*>(cert_params.subject_name.get()))) { 270 return TranslateLastOpenSslError(); 271 } 272 273 if (!X509_set_issuer_name(certificate.get(), const_cast<X509_NAME*>(issuer))) { 274 return TranslateLastOpenSslError(); 275 } 276 277 // Set activation date. 278 ASN1_TIME_Ptr notBefore(ASN1_TIME_new()); 279 LOG_D("Setting notBefore to %ld: ", cert_params.active_date_time / 1000); 280 time_t notBeforeTime = static_cast<time_t>(cert_params.active_date_time / 1000); 281 if (!notBefore.get() || !ASN1_TIME_set(notBefore.get(), notBeforeTime) || 282 !X509_set_notBefore(certificate.get(), notBefore.get() /* Don't release; copied */)) { 283 return TranslateLastOpenSslError(); 284 } 285 286 // Set expiration date. 287 ASN1_TIME_Ptr notAfter(ASN1_TIME_new()); 288 LOG_D("Setting notAfter to %ld: ", cert_params.expire_date_time / 1000); 289 time_t notAfterTime = static_cast<time_t>(cert_params.expire_date_time / 1000); 290 291 if (!notAfter.get() || !ASN1_TIME_set(notAfter.get(), notAfterTime) || 292 !X509_set_notAfter(certificate.get(), notAfter.get() /* Don't release; copied */)) { 293 return TranslateLastOpenSslError(); 294 } 295 296 *cert_out = move(certificate); 297 return KM_ERROR_OK; 298 } 299 300 keymaster_error_t make_cert(const EVP_PKEY* evp_pkey, const X509_NAME* issuer, 301 const CertificateCallerParams& cert_params, X509_Ptr* cert_out) { 302 303 // Make the rump certificate with serial, subject, not before and not after dates. 304 X509_Ptr certificate; 305 if (keymaster_error_t error = make_cert_rump(issuer, cert_params, &certificate)) { 306 return error; 307 } 308 309 // Set the public key. 310 if (!X509_set_pubkey(certificate.get(), (EVP_PKEY*)evp_pkey)) { 311 return TranslateLastOpenSslError(); 312 } 313 314 // Make and add the key usage extension. 315 X509_EXTENSION_Ptr key_usage_extension; 316 if (auto error = 317 make_key_usage_extension(cert_params.is_signing_key, cert_params.is_encryption_key, 318 cert_params.is_agreement_key, &key_usage_extension)) { 319 return error; 320 } 321 if (!X509_add_ext(certificate.get(), key_usage_extension.get() /* Don't release; copied */, 322 -1 /* insert at end */)) { 323 return TranslateLastOpenSslError(); 324 } 325 326 *cert_out = move(certificate); 327 return KM_ERROR_OK; 328 } 329 330 keymaster_error_t sign_cert(X509* certificate, const EVP_PKEY* signing_key) { 331 if (!certificate || !signing_key) return KM_ERROR_UNEXPECTED_NULL_POINTER; 332 333 // X509_sign takes the key as non-const, but per the BoringSSL dev team, that's a legacy 334 // mistake that hasn't yet been corrected. 335 auto sk = const_cast<EVP_PKEY*>(signing_key); 336 337 if (!X509_sign(certificate, sk, EVP_sha256())) { 338 return TranslateLastOpenSslError(); 339 } 340 return KM_ERROR_OK; 341 } 342 343 CertificateChain generate_self_signed_cert(const AsymmetricKey& key, const AuthorizationSet& params, 344 bool fake_signature, keymaster_error_t* error) { 345 keymaster_error_t err; 346 if (!error) error = &err; 347 348 EVP_PKEY_Ptr pkey(EVP_PKEY_new()); 349 if (!key.InternalToEvp(pkey.get())) { 350 *error = TranslateLastOpenSslError(); 351 return {}; 352 } 353 354 CertificateCallerParams cert_params{}; 355 // Self signed certificates are only generated since Keymint 1.0. To keep the API stable for 356 // now, we pass KEYMINT_1 to get_certificate_params, which has the intended effect. If 357 // get_certificate_params ever has to distinguish between versions of KeyMint this needs to be 358 // changed. 359 *error = get_certificate_params(params, &cert_params, KmVersion::KEYMINT_1); 360 if (*error != KM_ERROR_OK) return {}; 361 362 cert_params.is_signing_key = 363 (key.authorizations().Contains(TAG_PURPOSE, KM_PURPOSE_SIGN) || 364 key.authorizations().Contains(TAG_PURPOSE, KM_PURPOSE_ATTEST_KEY)); 365 cert_params.is_encryption_key = key.authorizations().Contains(TAG_PURPOSE, KM_PURPOSE_DECRYPT); 366 cert_params.is_agreement_key = key.authorizations().Contains(TAG_PURPOSE, KM_PURPOSE_AGREE_KEY); 367 368 X509_Ptr cert; 369 *error = make_cert(pkey.get(), cert_params.subject_name.get() /* issuer */, cert_params, &cert); 370 if (*error != KM_ERROR_OK) return {}; 371 372 if (fake_signature) { 373 *error = fake_sign_cert(cert.get()); 374 } else { 375 *error = sign_cert(cert.get(), pkey.get()); 376 } 377 if (*error != KM_ERROR_OK) return {}; 378 379 CertificateChain result(1); 380 if (!result) { 381 *error = KM_ERROR_MEMORY_ALLOCATION_FAILED; 382 return {}; 383 } 384 385 *error = encode_certificate(cert.get(), &result.entries[0]); 386 if (*error != KM_ERROR_OK) return {}; 387 388 return result; 389 } 390 391 keymaster_error_t encode_certificate(X509* certificate, keymaster_blob_t* blob) { 392 int len = i2d_X509(certificate, nullptr /* ppout */); 393 if (len < 0) return TranslateLastOpenSslError(); 394 395 blob->data = new (std::nothrow) uint8_t[len]; 396 if (!blob->data) return KM_ERROR_MEMORY_ALLOCATION_FAILED; 397 398 uint8_t* p = const_cast<uint8_t*>(blob->data); 399 blob->data_length = i2d_X509(certificate, &p); 400 return KM_ERROR_OK; 401 } 402 403 } // namespace keymaster 404