attestation_utils.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. #include <keymaster/km_openssl/attestation_utils.h>
  18. #include <hardware/keymaster_defs.h>
  19. #include <keymaster/authorization_set.h>
  20. #include <keymaster/attestation_record.h>
  21. #include <keymaster/km_openssl/asymmetric_key.h>
  22. #include <keymaster/km_openssl/openssl_utils.h>
  23. #include <keymaster/km_openssl/openssl_err.h>
  24. #include <openssl/x509v3.h>
  25. #include <openssl/evp.h>
  26. namespace keymaster {
  27. namespace {
  28. constexpr int kDigitalSignatureKeyUsageBit = 0;
  29. constexpr int kKeyEnciphermentKeyUsageBit = 2;
  30. constexpr int kDataEnciphermentKeyUsageBit = 3;
  31. constexpr int kMaxKeyUsageBit = 8;
  32. template <typename T> T && min(T && a, T && b) {
  33. return (a < b) ? forward<T>(a) : forward<T>(b);
  34. }
  35. struct emptyCert {};
  36. __attribute__((__unused__))
  37. inline keymaster_blob_t certBlobifier(const emptyCert&, bool*){ return {}; }
  38. template <size_t N>
  39. inline keymaster_blob_t certBlobifier(const uint8_t (&cert)[N], bool* fail){
  40. keymaster_blob_t result = { dup_array(cert), N };
  41. if (!result.data) {
  42. *fail = true;
  43. return {};
  44. }
  45. return result;
  46. }
  47. inline keymaster_blob_t certBlobifier(const keymaster_blob_t& blob, bool* fail){
  48. if (blob.data == nullptr || blob.data_length == 0) return {};
  49. keymaster_blob_t result = { dup_array(blob.data, blob.data_length), blob.data_length };
  50. if (!result.data) {
  51. *fail = true;
  52. return {};
  53. }
  54. return result;
  55. }
  56. inline keymaster_blob_t certBlobifier(keymaster_blob_t&& blob, bool*){
  57. if (blob.data == nullptr || blob.data_length == 0) return {};
  58. keymaster_blob_t result = blob;
  59. blob = {};
  60. return result;
  61. }
  62. inline keymaster_blob_t certBlobifier(X509* certificate, bool* fail){
  63. int len = i2d_X509(certificate, nullptr);
  64. if (len < 0) {
  65. *fail = true;
  66. return {};
  67. }
  68. uint8_t* data = new(std::nothrow) uint8_t[len];
  69. if (!data) {
  70. *fail = true;
  71. return {};
  72. }
  73. uint8_t* p = data;
  74. i2d_X509(certificate, &p);
  75. return { data, (size_t)len };
  76. }
  77. inline bool certCopier(keymaster_blob_t** out, const keymaster_cert_chain_t& chain,
  78. bool* fail) {
  79. for (size_t i = 0; i < chain.entry_count; ++i) {
  80. *(*out)++ = certBlobifier(chain.entries[i], fail);
  81. }
  82. return *fail;
  83. }
  84. __attribute__((__unused__))
  85. inline bool certCopier(keymaster_blob_t** out, keymaster_cert_chain_t&& chain, bool* fail) {
  86. for (size_t i = 0; i < chain.entry_count; ++i) {
  87. *(*out)++ = certBlobifier(move(chain.entries[i]), fail);
  88. }
  89. delete[] chain.entries;
  90. chain.entries = nullptr;
  91. chain.entry_count = 0;
  92. return *fail;
  93. }
  94. template <typename CERT>
  95. inline bool certCopier(keymaster_blob_t** out, CERT&& cert, bool* fail) {
  96. *(*out)++ = certBlobifier(forward<CERT>(cert), fail);
  97. return *fail;
  98. }
  99. inline bool certCopyHelper(keymaster_blob_t**, bool* fail) {
  100. return *fail;
  101. }
  102. template <typename CERT, typename... CERTS>
  103. inline bool certCopyHelper(keymaster_blob_t** out, bool* fail, CERT&& cert, CERTS&&... certs) {
  104. certCopier(out, forward<CERT>(cert), fail);
  105. return certCopyHelper(out, fail, forward<CERTS>(certs)...);
  106. }
  107. template <typename T>
  108. inline size_t noOfCert(T &&) { return 1; }
  109. inline size_t noOfCert(const keymaster_cert_chain_t& cert_chain) { return cert_chain.entry_count; }
  110. inline size_t certCount() { return 0; }
  111. template <typename CERT, typename... CERTS>
  112. inline size_t certCount(CERT&& cert, CERTS&&... certs) {
  113. return noOfCert(forward<CERT>(cert)) + certCount(forward<CERTS>(certs)...);
  114. }
  115. /*
  116. * makeCertChain creates a new keymaster_cert_chain_t from all the certs that get thrown at it
  117. * in the given order. A cert may be a X509*, uint8_t[], a keymaster_blob_t, an instance of
  118. * emptyCert, or another keymater_cert_chain_t in which case the certs of the chain are included
  119. * in the new chain. emptyCert is a placeholder which results in an empty slot at the given
  120. * position in the newly created certificate chain. E.g., makeCertChain(emptyCert(), someCertChain)
  121. * allocates enough slots to accommodate all certificates of someCertChain plus one empty slot and
  122. * copies in someCertChain starting at index 1 so that the slot with index 0 can be used for a new
  123. * leaf entry.
  124. *
  125. * makeCertChain respects move semantics. E.g., makeCertChain(emptyCert(), std::move(someCertChain))
  126. * will take possession of secondary resources for the certificate blobs so that someCertChain is
  127. * empty after the call. Also, because no allocation happens this cannot fail. Note, however, that
  128. * if another cert is passed to makeCertChain, that needs to be copied and thus requires
  129. * allocation, and this allocation fails, all resources - allocated or moved - will be reaped.
  130. */
  131. template <typename... CERTS>
  132. CertChainPtr makeCertChain(CERTS&&... certs) {
  133. CertChainPtr result(new (std::nothrow) keymaster_cert_chain_t);
  134. if (!result.get()) return {};
  135. result->entries = new (std::nothrow) keymaster_blob_t[certCount(forward<CERTS>(certs)...)];
  136. if (!result->entries) return {};
  137. result->entry_count = certCount(forward<CERTS>(certs)...);
  138. bool allocation_failed = false;
  139. keymaster_blob_t* entries = result->entries;
  140. certCopyHelper(&entries, &allocation_failed, forward<CERTS>(certs)...);
  141. if (allocation_failed) return {};
  142. return result;
  143. }
  144. keymaster_error_t build_attestation_extension(const AuthorizationSet& attest_params,
  145. const AuthorizationSet& tee_enforced,
  146. const AuthorizationSet& sw_enforced,
  147. const AttestationRecordContext& context,
  148. X509_EXTENSION_Ptr* extension) {
  149. ASN1_OBJECT_Ptr oid(
  150. OBJ_txt2obj(kAttestionRecordOid, 1 /* accept numerical dotted string form only */));
  151. if (!oid.get())
  152. return TranslateLastOpenSslError();
  153. UniquePtr<uint8_t[]> attest_bytes;
  154. size_t attest_bytes_len;
  155. keymaster_error_t error = build_attestation_record(attest_params, sw_enforced, tee_enforced,
  156. context, &attest_bytes, &attest_bytes_len);
  157. if (error != KM_ERROR_OK)
  158. return error;
  159. ASN1_OCTET_STRING_Ptr attest_str(ASN1_OCTET_STRING_new());
  160. if (!attest_str.get() ||
  161. !ASN1_OCTET_STRING_set(attest_str.get(), attest_bytes.get(), attest_bytes_len))
  162. return TranslateLastOpenSslError();
  163. extension->reset(
  164. X509_EXTENSION_create_by_OBJ(nullptr, oid.get(), 0 /* not critical */, attest_str.get()));
  165. if (!extension->get())
  166. return TranslateLastOpenSslError();
  167. return KM_ERROR_OK;
  168. }
  169. keymaster_error_t add_key_usage_extension(const AuthorizationSet& tee_enforced,
  170. const AuthorizationSet& sw_enforced,
  171. X509* certificate) {
  172. // Build BIT_STRING with correct contents.
  173. ASN1_BIT_STRING_Ptr key_usage(ASN1_BIT_STRING_new());
  174. if (!key_usage) return KM_ERROR_MEMORY_ALLOCATION_FAILED;
  175. for (size_t i = 0; i <= kMaxKeyUsageBit; ++i) {
  176. if (!ASN1_BIT_STRING_set_bit(key_usage.get(), i, 0)) {
  177. return TranslateLastOpenSslError();
  178. }
  179. }
  180. if (tee_enforced.Contains(TAG_PURPOSE, KM_PURPOSE_SIGN) ||
  181. tee_enforced.Contains(TAG_PURPOSE, KM_PURPOSE_VERIFY) ||
  182. sw_enforced.Contains(TAG_PURPOSE, KM_PURPOSE_SIGN) ||
  183. sw_enforced.Contains(TAG_PURPOSE, KM_PURPOSE_VERIFY)) {
  184. if (!ASN1_BIT_STRING_set_bit(key_usage.get(), kDigitalSignatureKeyUsageBit, 1)) {
  185. return TranslateLastOpenSslError();
  186. }
  187. }
  188. if (tee_enforced.Contains(TAG_PURPOSE, KM_PURPOSE_ENCRYPT) ||
  189. tee_enforced.Contains(TAG_PURPOSE, KM_PURPOSE_DECRYPT) ||
  190. sw_enforced.Contains(TAG_PURPOSE, KM_PURPOSE_ENCRYPT) ||
  191. sw_enforced.Contains(TAG_PURPOSE, KM_PURPOSE_DECRYPT)) {
  192. if (!ASN1_BIT_STRING_set_bit(key_usage.get(), kKeyEnciphermentKeyUsageBit, 1) ||
  193. !ASN1_BIT_STRING_set_bit(key_usage.get(), kDataEnciphermentKeyUsageBit, 1)) {
  194. return TranslateLastOpenSslError();
  195. }
  196. }
  197. // Convert to octets
  198. int len = i2d_ASN1_BIT_STRING(key_usage.get(), nullptr);
  199. if (len < 0) {
  200. return TranslateLastOpenSslError();
  201. }
  202. UniquePtr<uint8_t[]> asn1_key_usage(new(std::nothrow) uint8_t[len]);
  203. if (!asn1_key_usage.get()) {
  204. return KM_ERROR_MEMORY_ALLOCATION_FAILED;
  205. }
  206. uint8_t* p = asn1_key_usage.get();
  207. len = i2d_ASN1_BIT_STRING(key_usage.get(), &p);
  208. if (len < 0) {
  209. return TranslateLastOpenSslError();
  210. }
  211. // Build OCTET_STRING
  212. ASN1_OCTET_STRING_Ptr key_usage_str(ASN1_OCTET_STRING_new());
  213. if (!key_usage_str.get() ||
  214. !ASN1_OCTET_STRING_set(key_usage_str.get(), asn1_key_usage.get(), len)) {
  215. return TranslateLastOpenSslError();
  216. }
  217. X509_EXTENSION_Ptr key_usage_extension(X509_EXTENSION_create_by_NID(nullptr, //
  218. NID_key_usage, //
  219. false /* critical */,
  220. key_usage_str.get()));
  221. if (!key_usage_extension.get()) {
  222. return TranslateLastOpenSslError();
  223. }
  224. if (!X509_add_ext(certificate, key_usage_extension.get() /* Don't release; copied */,
  225. -1 /* insert at end */)) {
  226. return TranslateLastOpenSslError();
  227. }
  228. return KM_ERROR_OK;
  229. }
  230. bool add_public_key(EVP_PKEY* key, X509* certificate, keymaster_error_t* error) {
  231. if (!X509_set_pubkey(certificate, key)) {
  232. *error = TranslateLastOpenSslError();
  233. return false;
  234. }
  235. return true;
  236. }
  237. bool add_attestation_extension(const AuthorizationSet& attest_params,
  238. const AuthorizationSet& tee_enforced,
  239. const AuthorizationSet& sw_enforced,
  240. const AttestationRecordContext& context,
  241. X509* certificate,
  242. keymaster_error_t* error) {
  243. X509_EXTENSION_Ptr attest_extension;
  244. *error = build_attestation_extension(attest_params, tee_enforced, sw_enforced, context,
  245. &attest_extension);
  246. if (*error != KM_ERROR_OK)
  247. return false;
  248. if (!X509_add_ext(certificate, attest_extension.get() /* Don't release; copied */,
  249. -1 /* insert at end */)) {
  250. *error = TranslateLastOpenSslError();
  251. return false;
  252. }
  253. return true;
  254. }
  255. } // anonymous namespace
  256. keymaster_error_t generate_attestation(const AsymmetricKey& key,
  257. const AuthorizationSet& attest_params, const keymaster_cert_chain_t& attestation_chain,
  258. const keymaster_key_blob_t& attestation_signing_key,
  259. const AttestationRecordContext& context, CertChainPtr* cert_chain_out) {
  260. if (!cert_chain_out)
  261. return KM_ERROR_UNEXPECTED_NULL_POINTER;
  262. keymaster_algorithm_t sign_algorithm;
  263. if ((!key.sw_enforced().GetTagValue(TAG_ALGORITHM, &sign_algorithm) &&
  264. !key.hw_enforced().GetTagValue(TAG_ALGORITHM, &sign_algorithm)))
  265. return KM_ERROR_UNKNOWN_ERROR;
  266. EVP_PKEY_Ptr pkey(EVP_PKEY_new());
  267. if (!key.InternalToEvp(pkey.get()))
  268. return TranslateLastOpenSslError();
  269. X509_Ptr certificate(X509_new());
  270. if (!certificate.get())
  271. return TranslateLastOpenSslError();
  272. if (!X509_set_version(certificate.get(), 2 /* version 3, but zero-based */))
  273. return TranslateLastOpenSslError();
  274. ASN1_INTEGER_Ptr serialNumber(ASN1_INTEGER_new());
  275. if (!serialNumber.get() || !ASN1_INTEGER_set(serialNumber.get(), 1) ||
  276. !X509_set_serialNumber(certificate.get(), serialNumber.get() /* Don't release; copied */))
  277. return TranslateLastOpenSslError();
  278. X509_NAME_Ptr subjectName(X509_NAME_new());
  279. if (!subjectName.get() ||
  280. !X509_NAME_add_entry_by_txt(subjectName.get(), "CN", MBSTRING_ASC,
  281. reinterpret_cast<const uint8_t*>("Android Keystore Key"),
  282. -1 /* len */, -1 /* loc */, 0 /* set */) ||
  283. !X509_set_subject_name(certificate.get(), subjectName.get() /* Don't release; copied */))
  284. return TranslateLastOpenSslError();
  285. ASN1_TIME_Ptr notBefore(ASN1_TIME_new());
  286. uint64_t activeDateTime = 0;
  287. key.authorizations().GetTagValue(TAG_ACTIVE_DATETIME, &activeDateTime);
  288. if (!notBefore.get() || !ASN1_TIME_set(notBefore.get(), activeDateTime / 1000) ||
  289. !X509_set_notBefore(certificate.get(), notBefore.get() /* Don't release; copied */))
  290. return TranslateLastOpenSslError();
  291. ASN1_TIME_Ptr notAfter(ASN1_TIME_new());
  292. uint64_t usageExpireDateTime = UINT64_MAX;
  293. key.authorizations().GetTagValue(TAG_USAGE_EXPIRE_DATETIME, &usageExpireDateTime);
  294. // TODO(swillden): When trusty can use the C++ standard library change the calculation of
  295. // notAfterTime to use std::numeric_limits<time_t>::max(), rather than assuming that time_t is
  296. // 32 bits.
  297. time_t notAfterTime = min(static_cast<uint64_t>(UINT32_MAX), usageExpireDateTime / 1000);
  298. if (!notAfter.get() || !ASN1_TIME_set(notAfter.get(), notAfterTime) ||
  299. !X509_set_notAfter(certificate.get(), notAfter.get() /* Don't release; copied */))
  300. return TranslateLastOpenSslError();
  301. keymaster_error_t error = add_key_usage_extension(key.hw_enforced(), key.sw_enforced(), certificate.get());
  302. if (error != KM_ERROR_OK) {
  303. return error;
  304. }
  305. // We have established above that it is one of the two. So if it is not RSA its EC.
  306. int evp_key_type = (sign_algorithm == KM_ALGORITHM_RSA) ? EVP_PKEY_RSA : EVP_PKEY_EC;
  307. const uint8_t* key_material = attestation_signing_key.key_material;
  308. EVP_PKEY_Ptr sign_key(
  309. d2i_PrivateKey(evp_key_type, nullptr,
  310. const_cast<const uint8_t**>(&key_material),
  311. attestation_signing_key.key_material_size));
  312. if (!sign_key.get()) return TranslateLastOpenSslError();
  313. if (!add_public_key(pkey.get(), certificate.get(), &error) ||
  314. !add_attestation_extension(attest_params, key.hw_enforced(), key.sw_enforced(),
  315. context, certificate.get(), &error))
  316. return error;
  317. if (attestation_chain.entry_count < 1) {
  318. // the attestation chain must have at least the cert for the key that signs the new cert.
  319. return KM_ERROR_UNKNOWN_ERROR;
  320. }
  321. const uint8_t* p = attestation_chain.entries[0].data;
  322. X509_Ptr signing_cert(d2i_X509(nullptr, &p, attestation_chain.entries[0].data_length));
  323. if (!signing_cert.get()) {
  324. return TranslateLastOpenSslError();
  325. }
  326. // Set issuer to subject of batch certificate.
  327. X509_NAME* issuerSubject = X509_get_subject_name(signing_cert.get());
  328. if (!issuerSubject) {
  329. return KM_ERROR_UNKNOWN_ERROR;
  330. }
  331. if (!X509_set_issuer_name(certificate.get(), issuerSubject)) {
  332. return TranslateLastOpenSslError();
  333. }
  334. UniquePtr<X509V3_CTX> x509v3_ctx(new(std::nothrow) X509V3_CTX);
  335. if (!x509v3_ctx.get())
  336. return KM_ERROR_MEMORY_ALLOCATION_FAILED;
  337. *x509v3_ctx = {};
  338. X509V3_set_ctx(x509v3_ctx.get(), signing_cert.get(), certificate.get(), nullptr /* req */,
  339. nullptr /* crl */, 0 /* flags */);
  340. X509_EXTENSION_Ptr auth_key_id(X509V3_EXT_nconf_nid(nullptr /* conf */, x509v3_ctx.get(),
  341. NID_authority_key_identifier,
  342. const_cast<char*>("keyid:always")));
  343. if (!auth_key_id.get() ||
  344. !X509_add_ext(certificate.get(), auth_key_id.get() /* Don't release; copied */,
  345. -1 /* insert at end */)) {
  346. return TranslateLastOpenSslError();
  347. }
  348. if (!X509_sign(certificate.get(), sign_key.get(), EVP_sha256()))
  349. return TranslateLastOpenSslError();
  350. *cert_chain_out = makeCertChain(certificate.get(), attestation_chain);
  351. if (!cert_chain_out->get())
  352. return KM_ERROR_MEMORY_ALLOCATION_FAILED;
  353. return KM_ERROR_OK;
  354. }
  355. } // namespace keymaster