Keymaster.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. /*
  2. * Copyright (C) 2016 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. #include "Keymaster.h"
  17. #include <android-base/logging.h>
  18. #include <keymasterV4_0/authorization_set.h>
  19. #include <keymasterV4_0/keymaster_utils.h>
  20. namespace android {
  21. namespace vold {
  22. using ::android::hardware::hidl_string;
  23. using ::android::hardware::hidl_vec;
  24. using ::android::hardware::keymaster::V4_0::SecurityLevel;
  25. KeymasterOperation::~KeymasterOperation() {
  26. if (mDevice) mDevice->abort(mOpHandle);
  27. }
  28. bool KeymasterOperation::updateCompletely(const char* input, size_t inputLen,
  29. const std::function<void(const char*, size_t)> consumer) {
  30. uint32_t inputConsumed = 0;
  31. km::ErrorCode km_error;
  32. auto hidlCB = [&](km::ErrorCode ret, uint32_t inputConsumedDelta,
  33. const hidl_vec<km::KeyParameter>& /*ignored*/,
  34. const hidl_vec<uint8_t>& _output) {
  35. km_error = ret;
  36. if (km_error != km::ErrorCode::OK) return;
  37. inputConsumed += inputConsumedDelta;
  38. consumer(reinterpret_cast<const char*>(&_output[0]), _output.size());
  39. };
  40. while (inputConsumed != inputLen) {
  41. size_t toRead = static_cast<size_t>(inputLen - inputConsumed);
  42. auto inputBlob = km::support::blob2hidlVec(
  43. reinterpret_cast<const uint8_t*>(&input[inputConsumed]), toRead);
  44. auto error = mDevice->update(mOpHandle, hidl_vec<km::KeyParameter>(), inputBlob,
  45. km::HardwareAuthToken(), km::VerificationToken(), hidlCB);
  46. if (!error.isOk()) {
  47. LOG(ERROR) << "update failed: " << error.description();
  48. mDevice = nullptr;
  49. return false;
  50. }
  51. if (km_error != km::ErrorCode::OK) {
  52. LOG(ERROR) << "update failed, code " << int32_t(km_error);
  53. mDevice = nullptr;
  54. return false;
  55. }
  56. if (inputConsumed > inputLen) {
  57. LOG(ERROR) << "update reported too much input consumed";
  58. mDevice = nullptr;
  59. return false;
  60. }
  61. }
  62. return true;
  63. }
  64. bool KeymasterOperation::finish(std::string* output) {
  65. km::ErrorCode km_error;
  66. auto hidlCb = [&](km::ErrorCode ret, const hidl_vec<km::KeyParameter>& /*ignored*/,
  67. const hidl_vec<uint8_t>& _output) {
  68. km_error = ret;
  69. if (km_error != km::ErrorCode::OK) return;
  70. if (output) output->assign(reinterpret_cast<const char*>(&_output[0]), _output.size());
  71. };
  72. auto error = mDevice->finish(mOpHandle, hidl_vec<km::KeyParameter>(), hidl_vec<uint8_t>(),
  73. hidl_vec<uint8_t>(), km::HardwareAuthToken(),
  74. km::VerificationToken(), hidlCb);
  75. mDevice = nullptr;
  76. if (!error.isOk()) {
  77. LOG(ERROR) << "finish failed: " << error.description();
  78. return false;
  79. }
  80. if (km_error != km::ErrorCode::OK) {
  81. LOG(ERROR) << "finish failed, code " << int32_t(km_error);
  82. return false;
  83. }
  84. return true;
  85. }
  86. /* static */ bool Keymaster::hmacKeyGenerated = false;
  87. Keymaster::Keymaster() {
  88. auto devices = KmDevice::enumerateAvailableDevices();
  89. if (!hmacKeyGenerated) {
  90. KmDevice::performHmacKeyAgreement(devices);
  91. hmacKeyGenerated = true;
  92. }
  93. for (auto& dev : devices) {
  94. // Do not use StrongBox for device encryption / credential encryption. If a security chip
  95. // is present it will have Weaver, which already strengthens CE. We get no additional
  96. // benefit from using StrongBox here, so skip it.
  97. if (dev->halVersion().securityLevel != SecurityLevel::STRONGBOX) {
  98. mDevice = std::move(dev);
  99. break;
  100. }
  101. }
  102. if (!mDevice) return;
  103. auto& version = mDevice->halVersion();
  104. LOG(INFO) << "Using " << version.keymasterName << " from " << version.authorName
  105. << " for encryption. Security level: " << toString(version.securityLevel)
  106. << ", HAL: " << mDevice->descriptor() << "/" << mDevice->instanceName();
  107. }
  108. bool Keymaster::generateKey(const km::AuthorizationSet& inParams, std::string* key) {
  109. km::ErrorCode km_error;
  110. auto hidlCb = [&](km::ErrorCode ret, const hidl_vec<uint8_t>& keyBlob,
  111. const km::KeyCharacteristics& /*ignored*/) {
  112. km_error = ret;
  113. if (km_error != km::ErrorCode::OK) return;
  114. if (key) key->assign(reinterpret_cast<const char*>(&keyBlob[0]), keyBlob.size());
  115. };
  116. auto error = mDevice->generateKey(inParams.hidl_data(), hidlCb);
  117. if (!error.isOk()) {
  118. LOG(ERROR) << "generate_key failed: " << error.description();
  119. return false;
  120. }
  121. if (km_error != km::ErrorCode::OK) {
  122. LOG(ERROR) << "generate_key failed, code " << int32_t(km_error);
  123. return false;
  124. }
  125. return true;
  126. }
  127. bool Keymaster::deleteKey(const std::string& key) {
  128. auto keyBlob = km::support::blob2hidlVec(key);
  129. auto error = mDevice->deleteKey(keyBlob);
  130. if (!error.isOk()) {
  131. LOG(ERROR) << "delete_key failed: " << error.description();
  132. return false;
  133. }
  134. if (error != km::ErrorCode::OK) {
  135. LOG(ERROR) << "delete_key failed, code " << int32_t(km::ErrorCode(error));
  136. return false;
  137. }
  138. return true;
  139. }
  140. bool Keymaster::upgradeKey(const std::string& oldKey, const km::AuthorizationSet& inParams,
  141. std::string* newKey) {
  142. auto oldKeyBlob = km::support::blob2hidlVec(oldKey);
  143. km::ErrorCode km_error;
  144. auto hidlCb = [&](km::ErrorCode ret, const hidl_vec<uint8_t>& upgradedKeyBlob) {
  145. km_error = ret;
  146. if (km_error != km::ErrorCode::OK) return;
  147. if (newKey)
  148. newKey->assign(reinterpret_cast<const char*>(&upgradedKeyBlob[0]),
  149. upgradedKeyBlob.size());
  150. };
  151. auto error = mDevice->upgradeKey(oldKeyBlob, inParams.hidl_data(), hidlCb);
  152. if (!error.isOk()) {
  153. LOG(ERROR) << "upgrade_key failed: " << error.description();
  154. return false;
  155. }
  156. if (km_error != km::ErrorCode::OK) {
  157. LOG(ERROR) << "upgrade_key failed, code " << int32_t(km_error);
  158. return false;
  159. }
  160. return true;
  161. }
  162. KeymasterOperation Keymaster::begin(km::KeyPurpose purpose, const std::string& key,
  163. const km::AuthorizationSet& inParams,
  164. const km::HardwareAuthToken& authToken,
  165. km::AuthorizationSet* outParams) {
  166. auto keyBlob = km::support::blob2hidlVec(key);
  167. uint64_t mOpHandle;
  168. km::ErrorCode km_error;
  169. auto hidlCb = [&](km::ErrorCode ret, const hidl_vec<km::KeyParameter>& _outParams,
  170. uint64_t operationHandle) {
  171. km_error = ret;
  172. if (km_error != km::ErrorCode::OK) return;
  173. if (outParams) *outParams = _outParams;
  174. mOpHandle = operationHandle;
  175. };
  176. auto error = mDevice->begin(purpose, keyBlob, inParams.hidl_data(), authToken, hidlCb);
  177. if (!error.isOk()) {
  178. LOG(ERROR) << "begin failed: " << error.description();
  179. return KeymasterOperation(km::ErrorCode::UNKNOWN_ERROR);
  180. }
  181. if (km_error != km::ErrorCode::OK) {
  182. LOG(ERROR) << "begin failed, code " << int32_t(km_error);
  183. return KeymasterOperation(km_error);
  184. }
  185. return KeymasterOperation(mDevice.get(), mOpHandle);
  186. }
  187. bool Keymaster::isSecure() {
  188. return mDevice->halVersion().securityLevel != km::SecurityLevel::SOFTWARE;
  189. }
  190. } // namespace vold
  191. } // namespace android
  192. using namespace ::android::vold;
  193. int keymaster_compatibility_cryptfs_scrypt() {
  194. Keymaster dev;
  195. if (!dev) {
  196. LOG(ERROR) << "Failed to initiate keymaster session";
  197. return -1;
  198. }
  199. return dev.isSecure();
  200. }
  201. static bool write_string_to_buf(const std::string& towrite, uint8_t* buffer, uint32_t buffer_size,
  202. uint32_t* out_size) {
  203. if (!buffer || !out_size) {
  204. LOG(ERROR) << "Missing target pointers";
  205. return false;
  206. }
  207. *out_size = towrite.size();
  208. if (buffer_size < towrite.size()) {
  209. LOG(ERROR) << "Buffer too small " << buffer_size << " < " << towrite.size();
  210. return false;
  211. }
  212. memset(buffer, '\0', buffer_size);
  213. std::copy(towrite.begin(), towrite.end(), buffer);
  214. return true;
  215. }
  216. static km::AuthorizationSet keyParams(uint32_t rsa_key_size, uint64_t rsa_exponent,
  217. uint32_t ratelimit) {
  218. return km::AuthorizationSetBuilder()
  219. .RsaSigningKey(rsa_key_size, rsa_exponent)
  220. .NoDigestOrPadding()
  221. .Authorization(km::TAG_BLOB_USAGE_REQUIREMENTS, km::KeyBlobUsageRequirements::STANDALONE)
  222. .Authorization(km::TAG_NO_AUTH_REQUIRED)
  223. .Authorization(km::TAG_MIN_SECONDS_BETWEEN_OPS, ratelimit);
  224. }
  225. int keymaster_create_key_for_cryptfs_scrypt(uint32_t rsa_key_size, uint64_t rsa_exponent,
  226. uint32_t ratelimit, uint8_t* key_buffer,
  227. uint32_t key_buffer_size, uint32_t* key_out_size) {
  228. if (key_out_size) {
  229. *key_out_size = 0;
  230. }
  231. Keymaster dev;
  232. if (!dev) {
  233. LOG(ERROR) << "Failed to initiate keymaster session";
  234. return -1;
  235. }
  236. std::string key;
  237. if (!dev.generateKey(keyParams(rsa_key_size, rsa_exponent, ratelimit), &key)) return -1;
  238. if (!write_string_to_buf(key, key_buffer, key_buffer_size, key_out_size)) return -1;
  239. return 0;
  240. }
  241. int keymaster_upgrade_key_for_cryptfs_scrypt(uint32_t rsa_key_size, uint64_t rsa_exponent,
  242. uint32_t ratelimit, const uint8_t* key_blob,
  243. size_t key_blob_size, uint8_t* key_buffer,
  244. uint32_t key_buffer_size, uint32_t* key_out_size) {
  245. if (key_out_size) {
  246. *key_out_size = 0;
  247. }
  248. Keymaster dev;
  249. if (!dev) {
  250. LOG(ERROR) << "Failed to initiate keymaster session";
  251. return -1;
  252. }
  253. std::string old_key(reinterpret_cast<const char*>(key_blob), key_blob_size);
  254. std::string new_key;
  255. if (!dev.upgradeKey(old_key, keyParams(rsa_key_size, rsa_exponent, ratelimit), &new_key))
  256. return -1;
  257. if (!write_string_to_buf(new_key, key_buffer, key_buffer_size, key_out_size)) return -1;
  258. return 0;
  259. }
  260. KeymasterSignResult keymaster_sign_object_for_cryptfs_scrypt(
  261. const uint8_t* key_blob, size_t key_blob_size, uint32_t ratelimit, const uint8_t* object,
  262. const size_t object_size, uint8_t** signature_buffer, size_t* signature_buffer_size) {
  263. Keymaster dev;
  264. if (!dev) {
  265. LOG(ERROR) << "Failed to initiate keymaster session";
  266. return KeymasterSignResult::error;
  267. }
  268. if (!key_blob || !object || !signature_buffer || !signature_buffer_size) {
  269. LOG(ERROR) << __FILE__ << ":" << __LINE__ << ":Invalid argument";
  270. return KeymasterSignResult::error;
  271. }
  272. km::AuthorizationSet outParams;
  273. std::string key(reinterpret_cast<const char*>(key_blob), key_blob_size);
  274. std::string input(reinterpret_cast<const char*>(object), object_size);
  275. std::string output;
  276. KeymasterOperation op;
  277. auto paramBuilder = km::AuthorizationSetBuilder().NoDigestOrPadding();
  278. while (true) {
  279. op = dev.begin(km::KeyPurpose::SIGN, key, paramBuilder, km::HardwareAuthToken(), &outParams);
  280. if (op.errorCode() == km::ErrorCode::KEY_RATE_LIMIT_EXCEEDED) {
  281. sleep(ratelimit);
  282. continue;
  283. } else
  284. break;
  285. }
  286. if (op.errorCode() == km::ErrorCode::KEY_REQUIRES_UPGRADE) {
  287. LOG(ERROR) << "Keymaster key requires upgrade";
  288. return KeymasterSignResult::upgrade;
  289. }
  290. if (op.errorCode() != km::ErrorCode::OK) {
  291. LOG(ERROR) << "Error starting keymaster signature transaction: " << int32_t(op.errorCode());
  292. return KeymasterSignResult::error;
  293. }
  294. if (!op.updateCompletely(input, &output)) {
  295. LOG(ERROR) << "Error sending data to keymaster signature transaction: "
  296. << uint32_t(op.errorCode());
  297. return KeymasterSignResult::error;
  298. }
  299. if (!op.finish(&output)) {
  300. LOG(ERROR) << "Error finalizing keymaster signature transaction: "
  301. << int32_t(op.errorCode());
  302. return KeymasterSignResult::error;
  303. }
  304. *signature_buffer = reinterpret_cast<uint8_t*>(malloc(output.size()));
  305. if (*signature_buffer == nullptr) {
  306. LOG(ERROR) << "Error allocation buffer for keymaster signature";
  307. return KeymasterSignResult::error;
  308. }
  309. *signature_buffer_size = output.size();
  310. std::copy(output.data(), output.data() + output.size(), *signature_buffer);
  311. return KeymasterSignResult::ok;
  312. }