keystore_cli_v2.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. // Copyright 2015 The Android Open Source Project
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include <chrono>
  15. #include <cstdio>
  16. #include <future>
  17. #include <memory>
  18. #include <string>
  19. #include <vector>
  20. #include <base/command_line.h>
  21. #include <base/files/file_util.h>
  22. #include <base/strings/string_number_conversions.h>
  23. #include <base/strings/string_split.h>
  24. #include <base/strings/string_util.h>
  25. #include <base/strings/utf_string_conversions.h>
  26. #include <base/threading/platform_thread.h>
  27. #include <keystore/keymaster_types.h>
  28. #include <keystore/keystore_client_impl.h>
  29. #include <android/hardware/confirmationui/1.0/types.h>
  30. #include <android/security/BnConfirmationPromptCallback.h>
  31. #include <android/security/keystore/IKeystoreService.h>
  32. #include <binder/IPCThreadState.h>
  33. #include <binder/IServiceManager.h>
  34. //#include <keystore/keystore.h>
  35. using base::CommandLine;
  36. using keystore::KeystoreClient;
  37. using android::sp;
  38. using android::String16;
  39. using android::security::keystore::IKeystoreService;
  40. using base::CommandLine;
  41. using ConfirmationResponseCode = android::hardware::confirmationui::V1_0::ResponseCode;
  42. namespace {
  43. using namespace keystore;
  44. struct TestCase {
  45. std::string name;
  46. bool required_for_brillo_pts;
  47. AuthorizationSet parameters;
  48. };
  49. void PrintUsageAndExit() {
  50. printf("Usage: keystore_client_v2 <command> [options]\n");
  51. printf("Commands: brillo-platform-test [--prefix=<test_name_prefix>] [--test_for_0_3]\n"
  52. " list-brillo-tests\n"
  53. " add-entropy --input=<entropy> [--seclevel=software|strongbox|tee(default)]\n"
  54. " generate --name=<key_name> [--seclevel=software|strongbox|tee(default)]\n"
  55. " get-chars --name=<key_name>\n"
  56. " export --name=<key_name>\n"
  57. " delete --name=<key_name>\n"
  58. " delete-all\n"
  59. " exists --name=<key_name>\n"
  60. " list [--prefix=<key_name_prefix>]\n"
  61. " list-apps-with-keys\n"
  62. " sign-verify --name=<key_name>\n"
  63. " [en|de]crypt --name=<key_name> --in=<file> --out=<file>\n"
  64. " [--seclevel=software|strongbox|tee(default)]\n"
  65. " confirmation --prompt_text=<PromptText> --extra_data=<hex>\n"
  66. " --locale=<locale> [--ui_options=<list_of_ints>]\n"
  67. " --cancel_after=<seconds>\n");
  68. exit(1);
  69. }
  70. std::unique_ptr<KeystoreClient> CreateKeystoreInstance() {
  71. return std::unique_ptr<KeystoreClient>(
  72. static_cast<KeystoreClient*>(new keystore::KeystoreClientImpl));
  73. }
  74. void PrintTags(const AuthorizationSet& parameters) {
  75. for (auto iter = parameters.begin(); iter != parameters.end(); ++iter) {
  76. auto tag_str = toString(iter->tag);
  77. printf(" %s\n", tag_str.c_str());
  78. }
  79. }
  80. void PrintKeyCharacteristics(const AuthorizationSet& hardware_enforced_characteristics,
  81. const AuthorizationSet& software_enforced_characteristics) {
  82. printf("Hardware:\n");
  83. PrintTags(hardware_enforced_characteristics);
  84. printf("Software:\n");
  85. PrintTags(software_enforced_characteristics);
  86. }
  87. bool TestKey(const std::string& name, bool required, const AuthorizationSet& parameters) {
  88. std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance();
  89. AuthorizationSet hardware_enforced_characteristics;
  90. AuthorizationSet software_enforced_characteristics;
  91. auto result =
  92. keystore->generateKey("tmp", parameters, 0 /*flags*/, &hardware_enforced_characteristics,
  93. &software_enforced_characteristics);
  94. const char kBoldRedAbort[] = "\033[1;31mABORT\033[0m";
  95. if (!result.isOk()) {
  96. LOG(ERROR) << "Failed to generate key: " << result;
  97. printf("[%s] %s\n", kBoldRedAbort, name.c_str());
  98. return false;
  99. }
  100. result = keystore->deleteKey("tmp");
  101. if (!result.isOk()) {
  102. LOG(ERROR) << "Failed to delete key: " << result;
  103. printf("[%s] %s\n", kBoldRedAbort, name.c_str());
  104. return false;
  105. }
  106. printf("===============================================================\n");
  107. printf("%s Key Characteristics:\n", name.c_str());
  108. PrintKeyCharacteristics(hardware_enforced_characteristics, software_enforced_characteristics);
  109. bool hardware_backed = (hardware_enforced_characteristics.size() > 0);
  110. if (software_enforced_characteristics.GetTagCount(TAG_ALGORITHM) > 0 ||
  111. software_enforced_characteristics.GetTagCount(TAG_KEY_SIZE) > 0 ||
  112. software_enforced_characteristics.GetTagCount(TAG_RSA_PUBLIC_EXPONENT) > 0) {
  113. VLOG(1) << "Hardware-backed key but required characteristics enforced in software.";
  114. hardware_backed = false;
  115. }
  116. const char kBoldRedFail[] = "\033[1;31mFAIL\033[0m";
  117. const char kBoldGreenPass[] = "\033[1;32mPASS\033[0m";
  118. const char kBoldYellowWarn[] = "\033[1;33mWARN\033[0m";
  119. printf("[%s] %s\n",
  120. hardware_backed ? kBoldGreenPass : (required ? kBoldRedFail : kBoldYellowWarn),
  121. name.c_str());
  122. return (hardware_backed || !required);
  123. }
  124. AuthorizationSet GetRSASignParameters(uint32_t key_size, bool sha256_only) {
  125. AuthorizationSetBuilder parameters;
  126. parameters.RsaSigningKey(key_size, 65537)
  127. .Digest(Digest::SHA_2_256)
  128. .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
  129. .Padding(PaddingMode::RSA_PSS)
  130. .Authorization(TAG_NO_AUTH_REQUIRED);
  131. if (!sha256_only) {
  132. parameters.Digest(Digest::SHA_2_224).Digest(Digest::SHA_2_384).Digest(Digest::SHA_2_512);
  133. }
  134. return std::move(parameters);
  135. }
  136. AuthorizationSet GetRSAEncryptParameters(uint32_t key_size) {
  137. AuthorizationSetBuilder parameters;
  138. parameters.RsaEncryptionKey(key_size, 65537)
  139. .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
  140. .Padding(PaddingMode::RSA_OAEP)
  141. .Authorization(TAG_NO_AUTH_REQUIRED);
  142. return std::move(parameters);
  143. }
  144. AuthorizationSet GetECDSAParameters(uint32_t key_size, bool sha256_only) {
  145. AuthorizationSetBuilder parameters;
  146. parameters.EcdsaSigningKey(key_size)
  147. .Digest(Digest::SHA_2_256)
  148. .Authorization(TAG_NO_AUTH_REQUIRED);
  149. if (!sha256_only) {
  150. parameters.Digest(Digest::SHA_2_224).Digest(Digest::SHA_2_384).Digest(Digest::SHA_2_512);
  151. }
  152. return std::move(parameters);
  153. }
  154. AuthorizationSet GetAESParameters(uint32_t key_size, bool with_gcm_mode) {
  155. AuthorizationSetBuilder parameters;
  156. parameters.AesEncryptionKey(key_size).Authorization(TAG_NO_AUTH_REQUIRED);
  157. if (with_gcm_mode) {
  158. parameters.Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
  159. .Authorization(TAG_MIN_MAC_LENGTH, 128);
  160. } else {
  161. parameters.Authorization(TAG_BLOCK_MODE, BlockMode::ECB);
  162. parameters.Authorization(TAG_BLOCK_MODE, BlockMode::CBC);
  163. parameters.Authorization(TAG_BLOCK_MODE, BlockMode::CTR);
  164. parameters.Padding(PaddingMode::NONE);
  165. }
  166. return std::move(parameters);
  167. }
  168. AuthorizationSet GetHMACParameters(uint32_t key_size, Digest digest) {
  169. AuthorizationSetBuilder parameters;
  170. parameters.HmacKey(key_size)
  171. .Digest(digest)
  172. .Authorization(TAG_MIN_MAC_LENGTH, 224)
  173. .Authorization(TAG_NO_AUTH_REQUIRED);
  174. return std::move(parameters);
  175. }
  176. std::vector<TestCase> GetTestCases() {
  177. TestCase test_cases[] = {
  178. {"RSA-2048 Sign", true, GetRSASignParameters(2048, true)},
  179. {"RSA-2048 Sign (more digests)", false, GetRSASignParameters(2048, false)},
  180. {"RSA-3072 Sign", false, GetRSASignParameters(3072, false)},
  181. {"RSA-4096 Sign", false, GetRSASignParameters(4096, false)},
  182. {"RSA-2048 Encrypt", true, GetRSAEncryptParameters(2048)},
  183. {"RSA-3072 Encrypt", false, GetRSAEncryptParameters(3072)},
  184. {"RSA-4096 Encrypt", false, GetRSAEncryptParameters(4096)},
  185. {"ECDSA-P256 Sign", true, GetECDSAParameters(256, true)},
  186. {"ECDSA-P256 Sign (more digests)", false, GetECDSAParameters(256, false)},
  187. {"ECDSA-P224 Sign", false, GetECDSAParameters(224, false)},
  188. {"ECDSA-P384 Sign", false, GetECDSAParameters(384, false)},
  189. {"ECDSA-P521 Sign", false, GetECDSAParameters(521, false)},
  190. {"AES-128", true, GetAESParameters(128, false)},
  191. {"AES-256", true, GetAESParameters(256, false)},
  192. {"AES-128-GCM", false, GetAESParameters(128, true)},
  193. {"AES-256-GCM", false, GetAESParameters(256, true)},
  194. {"HMAC-SHA256-16", true, GetHMACParameters(16, Digest::SHA_2_256)},
  195. {"HMAC-SHA256-32", true, GetHMACParameters(32, Digest::SHA_2_256)},
  196. {"HMAC-SHA256-64", false, GetHMACParameters(64, Digest::SHA_2_256)},
  197. {"HMAC-SHA224-32", false, GetHMACParameters(32, Digest::SHA_2_224)},
  198. {"HMAC-SHA384-32", false, GetHMACParameters(32, Digest::SHA_2_384)},
  199. {"HMAC-SHA512-32", false, GetHMACParameters(32, Digest::SHA_2_512)},
  200. };
  201. return std::vector<TestCase>(&test_cases[0], &test_cases[arraysize(test_cases)]);
  202. }
  203. int BrilloPlatformTest(const std::string& prefix, bool test_for_0_3) {
  204. const char kBoldYellowWarning[] = "\033[1;33mWARNING\033[0m";
  205. if (test_for_0_3) {
  206. printf("%s: Testing for keymaster v0.3. "
  207. "This does not meet Brillo requirements.\n",
  208. kBoldYellowWarning);
  209. }
  210. int test_count = 0;
  211. int fail_count = 0;
  212. std::vector<TestCase> test_cases = GetTestCases();
  213. for (const auto& test_case : test_cases) {
  214. if (!prefix.empty() &&
  215. !base::StartsWith(test_case.name, prefix, base::CompareCase::SENSITIVE)) {
  216. continue;
  217. }
  218. if (test_for_0_3 &&
  219. (base::StartsWith(test_case.name, "AES", base::CompareCase::SENSITIVE) ||
  220. base::StartsWith(test_case.name, "HMAC", base::CompareCase::SENSITIVE))) {
  221. continue;
  222. }
  223. ++test_count;
  224. if (!TestKey(test_case.name, test_case.required_for_brillo_pts, test_case.parameters)) {
  225. VLOG(1) << "Test failed: " << test_case.name;
  226. ++fail_count;
  227. }
  228. }
  229. return fail_count;
  230. }
  231. int ListTestCases() {
  232. const char kBoldGreenRequired[] = "\033[1;32mREQUIRED\033[0m";
  233. const char kBoldYellowRecommended[] = "\033[1;33mRECOMMENDED\033[0m";
  234. std::vector<TestCase> test_cases = GetTestCases();
  235. for (const auto& test_case : test_cases) {
  236. printf("%s : %s\n", test_case.name.c_str(),
  237. test_case.required_for_brillo_pts ? kBoldGreenRequired : kBoldYellowRecommended);
  238. }
  239. return 0;
  240. }
  241. std::string ReadFile(const std::string& filename) {
  242. std::string content;
  243. base::FilePath path(filename);
  244. if (!base::ReadFileToString(path, &content)) {
  245. printf("Failed to read file: %s\n", filename.c_str());
  246. exit(1);
  247. }
  248. return content;
  249. }
  250. void WriteFile(const std::string& filename, const std::string& content) {
  251. base::FilePath path(filename);
  252. int size = content.size();
  253. if (base::WriteFile(path, content.data(), size) != size) {
  254. printf("Failed to write file: %s\n", filename.c_str());
  255. exit(1);
  256. }
  257. }
  258. int AddEntropy(const std::string& input, int32_t flags) {
  259. std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance();
  260. int32_t result = keystore->addRandomNumberGeneratorEntropy(input, flags).getErrorCode();
  261. printf("AddEntropy: %d\n", result);
  262. return result;
  263. }
  264. // Note: auth_bound keys created with this tool will not be usable.
  265. int GenerateKey(const std::string& name, int32_t flags, bool auth_bound) {
  266. std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance();
  267. AuthorizationSetBuilder params;
  268. params.RsaSigningKey(2048, 65537)
  269. .Digest(Digest::SHA_2_224)
  270. .Digest(Digest::SHA_2_256)
  271. .Digest(Digest::SHA_2_384)
  272. .Digest(Digest::SHA_2_512)
  273. .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
  274. .Padding(PaddingMode::RSA_PSS);
  275. if (auth_bound) {
  276. // Gatekeeper normally generates the secure user id.
  277. // Using zero allows the key to be created, but it will not be usuable.
  278. params.Authorization(TAG_USER_SECURE_ID, 0);
  279. } else {
  280. params.Authorization(TAG_NO_AUTH_REQUIRED);
  281. }
  282. AuthorizationSet hardware_enforced_characteristics;
  283. AuthorizationSet software_enforced_characteristics;
  284. auto result = keystore->generateKey(name, params, flags, &hardware_enforced_characteristics,
  285. &software_enforced_characteristics);
  286. printf("GenerateKey: %d\n", result.getErrorCode());
  287. if (result.isOk()) {
  288. PrintKeyCharacteristics(hardware_enforced_characteristics,
  289. software_enforced_characteristics);
  290. }
  291. return result.getErrorCode();
  292. }
  293. int GetCharacteristics(const std::string& name) {
  294. std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance();
  295. AuthorizationSet hardware_enforced_characteristics;
  296. AuthorizationSet software_enforced_characteristics;
  297. auto result = keystore->getKeyCharacteristics(name, &hardware_enforced_characteristics,
  298. &software_enforced_characteristics);
  299. printf("GetCharacteristics: %d\n", result.getErrorCode());
  300. if (result.isOk()) {
  301. PrintKeyCharacteristics(hardware_enforced_characteristics,
  302. software_enforced_characteristics);
  303. }
  304. return result.getErrorCode();
  305. }
  306. int ExportKey(const std::string& name) {
  307. std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance();
  308. std::string data;
  309. int32_t result = keystore->exportKey(KeyFormat::X509, name, &data).getErrorCode();
  310. printf("ExportKey: %d (%zu)\n", result, data.size());
  311. return result;
  312. }
  313. int DeleteKey(const std::string& name) {
  314. std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance();
  315. int32_t result = keystore->deleteKey(name).getErrorCode();
  316. printf("DeleteKey: %d\n", result);
  317. return result;
  318. }
  319. int DeleteAllKeys() {
  320. std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance();
  321. int32_t result = keystore->deleteAllKeys().getErrorCode();
  322. printf("DeleteAllKeys: %d\n", result);
  323. return result;
  324. }
  325. int DoesKeyExist(const std::string& name) {
  326. std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance();
  327. printf("DoesKeyExist: %s\n", keystore->doesKeyExist(name) ? "yes" : "no");
  328. return 0;
  329. }
  330. int List(const std::string& prefix) {
  331. std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance();
  332. std::vector<std::string> key_list;
  333. if (!keystore->listKeys(prefix, &key_list)) {
  334. printf("ListKeys failed.\n");
  335. return 1;
  336. }
  337. printf("Keys:\n");
  338. for (const auto& key_name : key_list) {
  339. printf(" %s\n", key_name.c_str());
  340. }
  341. return 0;
  342. }
  343. int ListAppsWithKeys() {
  344. sp<android::IServiceManager> sm = android::initdefaultServiceManager();
  345. sp<android::IBinder> binder = sm->getService(String16("android.security.keystore"));
  346. sp<IKeystoreService> service = android::interface_cast<IKeystoreService>(binder);
  347. if (service == nullptr) {
  348. fprintf(stderr, "Error connecting to keystore service.\n");
  349. return 1;
  350. }
  351. int32_t aidl_return;
  352. ::std::vector<::std::string> uids;
  353. android::binder::Status status = service->listUidsOfAuthBoundKeys(&uids, &aidl_return);
  354. if (!status.isOk()) {
  355. fprintf(stderr, "Requesting uids of auth bound keys failed with error %s.\n",
  356. status.toString8().c_str());
  357. return 1;
  358. }
  359. if (!KeyStoreNativeReturnCode(aidl_return).isOk()) {
  360. fprintf(stderr, "Requesting uids of auth bound keys failed with code %d.\n", aidl_return);
  361. return 1;
  362. }
  363. printf("Apps with auth bound keys:\n");
  364. for (auto i = uids.begin(); i != uids.end(); ++i) {
  365. printf("%s\n", i->c_str());
  366. }
  367. return 0;
  368. }
  369. int SignAndVerify(const std::string& name) {
  370. std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance();
  371. AuthorizationSetBuilder sign_params;
  372. sign_params.Padding(PaddingMode::RSA_PKCS1_1_5_SIGN);
  373. sign_params.Digest(Digest::SHA_2_256);
  374. AuthorizationSet output_params;
  375. uint64_t handle;
  376. auto result =
  377. keystore->beginOperation(KeyPurpose::SIGN, name, sign_params, &output_params, &handle);
  378. if (!result.isOk()) {
  379. printf("Sign: BeginOperation failed: %d\n", result.getErrorCode());
  380. return result.getErrorCode();
  381. }
  382. AuthorizationSet empty_params;
  383. size_t num_input_bytes_consumed;
  384. std::string output_data;
  385. result = keystore->updateOperation(handle, empty_params, "data_to_sign",
  386. &num_input_bytes_consumed, &output_params, &output_data);
  387. if (!result.isOk()) {
  388. printf("Sign: UpdateOperation failed: %d\n", result.getErrorCode());
  389. return result.getErrorCode();
  390. }
  391. result = keystore->finishOperation(handle, empty_params, std::string() /*signature_to_verify*/,
  392. &output_params, &output_data);
  393. if (!result.isOk()) {
  394. printf("Sign: FinishOperation failed: %d\n", result.getErrorCode());
  395. return result.getErrorCode();
  396. }
  397. printf("Sign: %zu bytes.\n", output_data.size());
  398. // We have a signature, now verify it.
  399. std::string signature_to_verify = output_data;
  400. output_data.clear();
  401. result =
  402. keystore->beginOperation(KeyPurpose::VERIFY, name, sign_params, &output_params, &handle);
  403. if (!result.isOk()) {
  404. printf("Verify: BeginOperation failed: %d\n", result.getErrorCode());
  405. return result.getErrorCode();
  406. }
  407. result = keystore->updateOperation(handle, empty_params, "data_to_sign",
  408. &num_input_bytes_consumed, &output_params, &output_data);
  409. if (!result.isOk()) {
  410. printf("Verify: UpdateOperation failed: %d\n", result.getErrorCode());
  411. return result.getErrorCode();
  412. }
  413. result = keystore->finishOperation(handle, empty_params, signature_to_verify, &output_params,
  414. &output_data);
  415. if (result == ErrorCode::VERIFICATION_FAILED) {
  416. printf("Verify: Failed to verify signature.\n");
  417. return result.getErrorCode();
  418. }
  419. if (!result.isOk()) {
  420. printf("Verify: FinishOperation failed: %d\n", result.getErrorCode());
  421. return result.getErrorCode();
  422. }
  423. printf("Verify: OK\n");
  424. return 0;
  425. }
  426. int Encrypt(const std::string& key_name, const std::string& input_filename,
  427. const std::string& output_filename, int32_t flags) {
  428. std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance();
  429. std::string input = ReadFile(input_filename);
  430. std::string output;
  431. if (!keystore->encryptWithAuthentication(key_name, input, flags, &output)) {
  432. printf("EncryptWithAuthentication failed.\n");
  433. return 1;
  434. }
  435. WriteFile(output_filename, output);
  436. return 0;
  437. }
  438. int Decrypt(const std::string& key_name, const std::string& input_filename,
  439. const std::string& output_filename) {
  440. std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance();
  441. std::string input = ReadFile(input_filename);
  442. std::string output;
  443. if (!keystore->decryptWithAuthentication(key_name, input, &output)) {
  444. printf("DecryptWithAuthentication failed.\n");
  445. return 1;
  446. }
  447. WriteFile(output_filename, output);
  448. return 0;
  449. }
  450. uint32_t securityLevelOption2Flags(const CommandLine& cmd) {
  451. if (cmd.HasSwitch("seclevel")) {
  452. auto str = cmd.GetSwitchValueASCII("seclevel");
  453. if (str == "strongbox") {
  454. return KEYSTORE_FLAG_STRONGBOX;
  455. } else if (str == "software") {
  456. return KEYSTORE_FLAG_FALLBACK;
  457. }
  458. }
  459. return KEYSTORE_FLAG_NONE;
  460. }
  461. class ConfirmationListener
  462. : public android::security::BnConfirmationPromptCallback,
  463. public std::promise<std::tuple<ConfirmationResponseCode, std::vector<uint8_t>>> {
  464. public:
  465. ConfirmationListener() {}
  466. virtual ::android::binder::Status
  467. onConfirmationPromptCompleted(int32_t result,
  468. const ::std::vector<uint8_t>& dataThatWasConfirmed) override {
  469. this->set_value({static_cast<ConfirmationResponseCode>(result), dataThatWasConfirmed});
  470. return ::android::binder::Status::ok();
  471. }
  472. };
  473. int Confirmation(const std::string& promptText, const std::string& extraDataHex,
  474. const std::string& locale, const std::string& uiOptionsStr,
  475. const std::string& cancelAfter) {
  476. sp<android::IServiceManager> sm = android::initdefaultServiceManager();
  477. sp<android::IBinder> binder = sm->getService(String16("android.security.keystore"));
  478. sp<IKeystoreService> service = android::interface_cast<IKeystoreService>(binder);
  479. if (service == nullptr) {
  480. printf("error: could not connect to keystore service.\n");
  481. return 1;
  482. }
  483. if (promptText.size() == 0) {
  484. printf("The --prompt_text parameter cannot be empty.\n");
  485. return 1;
  486. }
  487. std::vector<uint8_t> extraData;
  488. if (!base::HexStringToBytes(extraDataHex, &extraData)) {
  489. printf("The --extra_data parameter does not appear to be valid hexadecimal.\n");
  490. return 1;
  491. }
  492. std::vector<std::string> pieces =
  493. base::SplitString(uiOptionsStr, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
  494. int uiOptionsAsFlags = 0;
  495. for (auto& p : pieces) {
  496. int value;
  497. if (!base::StringToInt(p, &value)) {
  498. printf("Error parsing %s in --ui_options parameter as a number.\n", p.c_str());
  499. return 1;
  500. }
  501. uiOptionsAsFlags |= (1 << value);
  502. }
  503. double cancelAfterValue = 0.0;
  504. if (cancelAfter.size() > 0 && !base::StringToDouble(cancelAfter, &cancelAfterValue)) {
  505. printf("Error parsing %s in --cancel_after parameter as a double.\n", cancelAfter.c_str());
  506. return 1;
  507. }
  508. String16 promptText16(promptText.data(), promptText.size());
  509. String16 locale16(locale.data(), locale.size());
  510. sp<ConfirmationListener> listener = new ConfirmationListener();
  511. auto future = listener->get_future();
  512. int32_t aidl_return;
  513. android::binder::Status status = service->presentConfirmationPrompt(
  514. listener, promptText16, extraData, locale16, uiOptionsAsFlags, &aidl_return);
  515. if (!status.isOk()) {
  516. printf("Presenting confirmation prompt failed with binder status '%s'.\n",
  517. status.toString8().c_str());
  518. return 1;
  519. }
  520. ConfirmationResponseCode responseCode = static_cast<ConfirmationResponseCode>(aidl_return);
  521. if (responseCode != ConfirmationResponseCode::OK) {
  522. printf("Presenting confirmation prompt failed with response code %d.\n", responseCode);
  523. return 1;
  524. }
  525. printf("Waiting for prompt to complete - use Ctrl+C to abort...\n");
  526. if (cancelAfterValue > 0.0) {
  527. printf("Sleeping %.1f seconds before canceling prompt...\n", cancelAfterValue);
  528. auto fstatus =
  529. future.wait_for(std::chrono::milliseconds(uint64_t(cancelAfterValue * 1000)));
  530. if (fstatus == std::future_status::timeout) {
  531. status = service->cancelConfirmationPrompt(listener, &aidl_return);
  532. if (!status.isOk()) {
  533. printf("Canceling confirmation prompt failed with binder status '%s'.\n",
  534. status.toString8().c_str());
  535. return 1;
  536. }
  537. responseCode = static_cast<ConfirmationResponseCode>(aidl_return);
  538. if (responseCode == ConfirmationResponseCode::Ignored) {
  539. // The confirmation was completed by the user so take the response
  540. } else if (responseCode != ConfirmationResponseCode::OK) {
  541. printf("Canceling confirmation prompt failed with response code %d.\n",
  542. responseCode);
  543. return 1;
  544. }
  545. }
  546. }
  547. future.wait();
  548. auto [rc, dataThatWasConfirmed] = future.get();
  549. printf("Confirmation prompt completed\n"
  550. "responseCode = %d\n",
  551. rc);
  552. printf("dataThatWasConfirmed[%zd] = {", dataThatWasConfirmed.size());
  553. size_t newLineCountDown = 16;
  554. bool hasPrinted = false;
  555. for (uint8_t element : dataThatWasConfirmed) {
  556. if (hasPrinted) {
  557. printf(", ");
  558. }
  559. if (newLineCountDown == 0) {
  560. printf("\n ");
  561. newLineCountDown = 32;
  562. }
  563. printf("0x%02x", element);
  564. hasPrinted = true;
  565. }
  566. printf("}\n");
  567. return 0;
  568. }
  569. } // namespace
  570. int main(int argc, char** argv) {
  571. CommandLine::Init(argc, argv);
  572. CommandLine* command_line = CommandLine::ForCurrentProcess();
  573. CommandLine::StringVector args = command_line->GetArgs();
  574. android::ProcessState::self()->startThreadPool();
  575. if (args.empty()) {
  576. PrintUsageAndExit();
  577. }
  578. if (args[0] == "brillo-platform-test") {
  579. return BrilloPlatformTest(command_line->GetSwitchValueASCII("prefix"),
  580. command_line->HasSwitch("test_for_0_3"));
  581. } else if (args[0] == "list-brillo-tests") {
  582. return ListTestCases();
  583. } else if (args[0] == "add-entropy") {
  584. return AddEntropy(command_line->GetSwitchValueASCII("input"),
  585. securityLevelOption2Flags(*command_line));
  586. } else if (args[0] == "generate") {
  587. return GenerateKey(command_line->GetSwitchValueASCII("name"),
  588. securityLevelOption2Flags(*command_line),
  589. command_line->HasSwitch("auth_bound"));
  590. } else if (args[0] == "get-chars") {
  591. return GetCharacteristics(command_line->GetSwitchValueASCII("name"));
  592. } else if (args[0] == "export") {
  593. return ExportKey(command_line->GetSwitchValueASCII("name"));
  594. } else if (args[0] == "delete") {
  595. return DeleteKey(command_line->GetSwitchValueASCII("name"));
  596. } else if (args[0] == "delete-all") {
  597. return DeleteAllKeys();
  598. } else if (args[0] == "exists") {
  599. return DoesKeyExist(command_line->GetSwitchValueASCII("name"));
  600. } else if (args[0] == "list") {
  601. return List(command_line->GetSwitchValueASCII("prefix"));
  602. } else if (args[0] == "list-apps-with-keys") {
  603. return ListAppsWithKeys();
  604. } else if (args[0] == "sign-verify") {
  605. return SignAndVerify(command_line->GetSwitchValueASCII("name"));
  606. } else if (args[0] == "encrypt") {
  607. return Encrypt(
  608. command_line->GetSwitchValueASCII("name"), command_line->GetSwitchValueASCII("in"),
  609. command_line->GetSwitchValueASCII("out"), securityLevelOption2Flags(*command_line));
  610. } else if (args[0] == "decrypt") {
  611. return Decrypt(command_line->GetSwitchValueASCII("name"),
  612. command_line->GetSwitchValueASCII("in"),
  613. command_line->GetSwitchValueASCII("out"));
  614. } else if (args[0] == "confirmation") {
  615. return Confirmation(command_line->GetSwitchValueNative("prompt_text"),
  616. command_line->GetSwitchValueASCII("extra_data"),
  617. command_line->GetSwitchValueASCII("locale"),
  618. command_line->GetSwitchValueASCII("ui_options"),
  619. command_line->GetSwitchValueASCII("cancel_after"));
  620. } else {
  621. PrintUsageAndExit();
  622. }
  623. return 0;
  624. }