• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
15 #include <cstdio>
16 #include <memory>
17 #include <string>
18 #include <vector>
19 
20 #include "base/command_line.h"
21 #include "base/files/file_util.h"
22 #include "base/strings/string_util.h"
23 #include "keystore/authorization_set.h"
24 #include "keystore/keymaster_tags.h"
25 #include "keystore/keystore_client_impl.h"
26 
27 using base::CommandLine;
28 using keystore::AuthorizationSet;
29 //using keymaster::AuthorizationSetBuilder;
30 using keystore::KeystoreClient;
31 
32 namespace {
33 using namespace keystore;
34 
35 struct TestCase {
36     std::string name;
37     bool required_for_brillo_pts;
38     AuthorizationSet parameters;
39 };
40 
PrintUsageAndExit()41 void PrintUsageAndExit() {
42     printf("Usage: keystore_client_v2 <command> [options]\n");
43     printf("Commands: brillo-platform-test [--prefix=<test_name_prefix>] [--test_for_0_3]\n"
44            "          list-brillo-tests\n"
45            "          add-entropy --input=<entropy>\n"
46            "          generate --name=<key_name>\n"
47            "          get-chars --name=<key_name>\n"
48            "          export --name=<key_name>\n"
49            "          delete --name=<key_name>\n"
50            "          delete-all\n"
51            "          exists --name=<key_name>\n"
52            "          list [--prefix=<key_name_prefix>]\n"
53            "          sign-verify --name=<key_name>\n"
54            "          [en|de]crypt --name=<key_name> --in=<file> --out=<file>\n");
55     exit(1);
56 }
57 
CreateKeystoreInstance()58 std::unique_ptr<KeystoreClient> CreateKeystoreInstance() {
59     return std::unique_ptr<KeystoreClient>(
60             static_cast<KeystoreClient*>(new keystore::KeystoreClientImpl));
61 }
62 
PrintTags(const AuthorizationSet & parameters)63 void PrintTags(const AuthorizationSet& parameters) {
64     for (auto iter = parameters.begin(); iter != parameters.end(); ++iter) {
65         printf("  %s\n", stringifyTag(iter->tag));
66     }
67 }
68 
PrintKeyCharacteristics(const AuthorizationSet & hardware_enforced_characteristics,const AuthorizationSet & software_enforced_characteristics)69 void PrintKeyCharacteristics(const AuthorizationSet& hardware_enforced_characteristics,
70                              const AuthorizationSet& software_enforced_characteristics) {
71     printf("Hardware:\n");
72     PrintTags(hardware_enforced_characteristics);
73     printf("Software:\n");
74     PrintTags(software_enforced_characteristics);
75 }
76 
TestKey(const std::string & name,bool required,const AuthorizationSet & parameters)77 bool TestKey(const std::string& name, bool required, const AuthorizationSet& parameters) {
78     std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance();
79     AuthorizationSet hardware_enforced_characteristics;
80     AuthorizationSet software_enforced_characteristics;
81     auto result = keystore->generateKey("tmp", parameters, &hardware_enforced_characteristics,
82                                            &software_enforced_characteristics);
83     const char kBoldRedAbort[] = "\033[1;31mABORT\033[0m";
84     if (!result.isOk()) {
85         LOG(ERROR) << "Failed to generate key: " << result;
86         printf("[%s] %s\n", kBoldRedAbort, name.c_str());
87         return false;
88     }
89     result = keystore->deleteKey("tmp");
90     if (!result.isOk()) {
91         LOG(ERROR) << "Failed to delete key: " << result;
92         printf("[%s] %s\n", kBoldRedAbort, name.c_str());
93         return false;
94     }
95     printf("===============================================================\n");
96     printf("%s Key Characteristics:\n", name.c_str());
97     PrintKeyCharacteristics(hardware_enforced_characteristics, software_enforced_characteristics);
98     bool hardware_backed = (hardware_enforced_characteristics.size() > 0);
99     if (software_enforced_characteristics.GetTagCount(TAG_ALGORITHM) > 0 ||
100         software_enforced_characteristics.GetTagCount(TAG_KEY_SIZE) > 0 ||
101         software_enforced_characteristics.GetTagCount(TAG_RSA_PUBLIC_EXPONENT) > 0) {
102         VLOG(1) << "Hardware-backed key but required characteristics enforced in software.";
103         hardware_backed = false;
104     }
105     const char kBoldRedFail[] = "\033[1;31mFAIL\033[0m";
106     const char kBoldGreenPass[] = "\033[1;32mPASS\033[0m";
107     const char kBoldYellowWarn[] = "\033[1;33mWARN\033[0m";
108     printf("[%s] %s\n",
109            hardware_backed ? kBoldGreenPass : (required ? kBoldRedFail : kBoldYellowWarn),
110            name.c_str());
111 
112     return (hardware_backed || !required);
113 }
114 
GetRSASignParameters(uint32_t key_size,bool sha256_only)115 AuthorizationSet GetRSASignParameters(uint32_t key_size, bool sha256_only) {
116     AuthorizationSetBuilder parameters;
117     parameters.RsaSigningKey(key_size, 65537)
118         .Digest(Digest::SHA_2_256)
119         .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
120         .Padding(PaddingMode::RSA_PSS)
121         .Authorization(TAG_NO_AUTH_REQUIRED);
122     if (!sha256_only) {
123         parameters.Digest(Digest::SHA_2_224)
124             .Digest(Digest::SHA_2_384)
125             .Digest(Digest::SHA_2_512);
126     }
127     return parameters;
128 }
129 
GetRSAEncryptParameters(uint32_t key_size)130 AuthorizationSet GetRSAEncryptParameters(uint32_t key_size) {
131     AuthorizationSetBuilder parameters;
132     parameters.RsaEncryptionKey(key_size, 65537)
133         .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
134         .Padding(PaddingMode::RSA_OAEP)
135         .Authorization(TAG_NO_AUTH_REQUIRED);
136     return parameters;
137 }
138 
GetECDSAParameters(uint32_t key_size,bool sha256_only)139 AuthorizationSet GetECDSAParameters(uint32_t key_size, bool sha256_only) {
140     AuthorizationSetBuilder parameters;
141     parameters.EcdsaSigningKey(key_size)
142         .Digest(Digest::SHA_2_256)
143         .Authorization(TAG_NO_AUTH_REQUIRED);
144     if (!sha256_only) {
145         parameters.Digest(Digest::SHA_2_224)
146             .Digest(Digest::SHA_2_384)
147             .Digest(Digest::SHA_2_512);
148     }
149     return parameters;
150 }
151 
GetAESParameters(uint32_t key_size,bool with_gcm_mode)152 AuthorizationSet GetAESParameters(uint32_t key_size, bool with_gcm_mode) {
153     AuthorizationSetBuilder parameters;
154     parameters.AesEncryptionKey(key_size).Authorization(TAG_NO_AUTH_REQUIRED);
155     if (with_gcm_mode) {
156         parameters.Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
157             .Authorization(TAG_MIN_MAC_LENGTH, 128);
158     } else {
159         parameters.Authorization(TAG_BLOCK_MODE, BlockMode::ECB);
160         parameters.Authorization(TAG_BLOCK_MODE, BlockMode::CBC);
161         parameters.Authorization(TAG_BLOCK_MODE, BlockMode::CTR);
162         parameters.Padding(PaddingMode::NONE);
163     }
164     return parameters;
165 }
166 
GetHMACParameters(uint32_t key_size,Digest digest)167 AuthorizationSet GetHMACParameters(uint32_t key_size, Digest digest) {
168     AuthorizationSetBuilder parameters;
169     parameters.HmacKey(key_size)
170         .Digest(digest)
171         .Authorization(TAG_MIN_MAC_LENGTH, 224)
172         .Authorization(TAG_NO_AUTH_REQUIRED);
173     return parameters;
174 }
175 
GetTestCases()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 
BrilloPlatformTest(const std::string & prefix,bool test_for_0_3)204 int BrilloPlatformTest(const std::string& prefix, bool test_for_0_3) {
205     const char kBoldYellowWarning[] = "\033[1;33mWARNING\033[0m";
206     if (test_for_0_3) {
207         printf("%s: Testing for keymaster v0.3. "
208                "This does not meet Brillo requirements.\n", 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 
ListTestCases()232 int ListTestCases() {
233     const char kBoldGreenRequired[] = "\033[1;32mREQUIRED\033[0m";
234     const char kBoldYellowRecommended[] = "\033[1;33mRECOMMENDED\033[0m";
235     std::vector<TestCase> test_cases = GetTestCases();
236     for (const auto& test_case : test_cases) {
237         printf("%s : %s\n", test_case.name.c_str(),
238                test_case.required_for_brillo_pts ? kBoldGreenRequired : kBoldYellowRecommended);
239     }
240     return 0;
241 }
242 
ReadFile(const std::string & filename)243 std::string ReadFile(const std::string& filename) {
244     std::string content;
245     base::FilePath path(filename);
246     if (!base::ReadFileToString(path, &content)) {
247         printf("Failed to read file: %s\n", filename.c_str());
248         exit(1);
249     }
250     return content;
251 }
252 
WriteFile(const std::string & filename,const std::string & content)253 void WriteFile(const std::string& filename, const std::string& content) {
254     base::FilePath path(filename);
255     int size = content.size();
256     if (base::WriteFile(path, content.data(), size) != size) {
257         printf("Failed to write file: %s\n", filename.c_str());
258         exit(1);
259     }
260 }
261 
AddEntropy(const std::string & input)262 int AddEntropy(const std::string& input) {
263     std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance();
264     int32_t result = keystore->addRandomNumberGeneratorEntropy(input);
265     printf("AddEntropy: %d\n", result);
266     return result;
267 }
268 
GenerateKey(const std::string & name)269 int GenerateKey(const std::string& name) {
270     std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance();
271     AuthorizationSetBuilder params;
272     params.RsaSigningKey(2048, 65537)
273         .Digest(Digest::SHA_2_224)
274         .Digest(Digest::SHA_2_256)
275         .Digest(Digest::SHA_2_384)
276         .Digest(Digest::SHA_2_512)
277         .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
278         .Padding(PaddingMode::RSA_PSS)
279         .Authorization(TAG_NO_AUTH_REQUIRED);
280     AuthorizationSet hardware_enforced_characteristics;
281     AuthorizationSet software_enforced_characteristics;
282     auto result = keystore->generateKey(name, params, &hardware_enforced_characteristics,
283                                            &software_enforced_characteristics);
284     printf("GenerateKey: %d\n", int32_t(result));
285     if (result.isOk()) {
286         PrintKeyCharacteristics(hardware_enforced_characteristics,
287                                 software_enforced_characteristics);
288     }
289     return result;
290 }
291 
GetCharacteristics(const std::string & name)292 int GetCharacteristics(const std::string& name) {
293     std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance();
294     AuthorizationSet hardware_enforced_characteristics;
295     AuthorizationSet software_enforced_characteristics;
296     auto result = keystore->getKeyCharacteristics(name, &hardware_enforced_characteristics,
297                                                      &software_enforced_characteristics);
298     printf("GetCharacteristics: %d\n", int32_t(result));
299     if (result.isOk()) {
300         PrintKeyCharacteristics(hardware_enforced_characteristics,
301                                 software_enforced_characteristics);
302     }
303     return result;
304 }
305 
ExportKey(const std::string & name)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);
310     printf("ExportKey: %d (%zu)\n", result, data.size());
311     return result;
312 }
313 
DeleteKey(const std::string & name)314 int DeleteKey(const std::string& name) {
315     std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance();
316     int32_t result = keystore->deleteKey(name);
317     printf("DeleteKey: %d\n", result);
318     return result;
319 }
320 
DeleteAllKeys()321 int DeleteAllKeys() {
322     std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance();
323     int32_t result = keystore->deleteAllKeys();
324     printf("DeleteAllKeys: %d\n", result);
325     return result;
326 }
327 
DoesKeyExist(const std::string & name)328 int DoesKeyExist(const std::string& name) {
329     std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance();
330     printf("DoesKeyExist: %s\n", keystore->doesKeyExist(name) ? "yes" : "no");
331     return 0;
332 }
333 
List(const std::string & prefix)334 int List(const std::string& prefix) {
335     std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance();
336     std::vector<std::string> key_list;
337     if (!keystore->listKeys(prefix, &key_list)) {
338         printf("ListKeys failed.\n");
339         return 1;
340     }
341     printf("Keys:\n");
342     for (const auto& key_name : key_list) {
343         printf("  %s\n", key_name.c_str());
344     }
345     return 0;
346 }
347 
SignAndVerify(const std::string & name)348 int SignAndVerify(const std::string& name) {
349     std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance();
350     AuthorizationSetBuilder sign_params;
351     sign_params.Padding(PaddingMode::RSA_PKCS1_1_5_SIGN);
352     sign_params.Digest(Digest::SHA_2_256);
353     AuthorizationSet output_params;
354     uint64_t handle;
355     auto result = keystore->beginOperation(KeyPurpose::SIGN, name, sign_params,
356                                               &output_params, &handle);
357     if (!result.isOk()) {
358         printf("Sign: BeginOperation failed: %d\n", int32_t(result));
359         return result;
360     }
361     AuthorizationSet empty_params;
362     size_t num_input_bytes_consumed;
363     std::string output_data;
364     result = keystore->updateOperation(handle, empty_params, "data_to_sign",
365                                        &num_input_bytes_consumed, &output_params, &output_data);
366     if (!result.isOk()) {
367         printf("Sign: UpdateOperation failed: %d\n", int32_t(result));
368         return result;
369     }
370     result = keystore->finishOperation(handle, empty_params, std::string() /*signature_to_verify*/,
371                                        &output_params, &output_data);
372     if (!result.isOk()) {
373         printf("Sign: FinishOperation failed: %d\n", int32_t(result));
374         return result;
375     }
376     printf("Sign: %zu bytes.\n", output_data.size());
377     // We have a signature, now verify it.
378     std::string signature_to_verify = output_data;
379     output_data.clear();
380     result = keystore->beginOperation(KeyPurpose::VERIFY, name, sign_params, &output_params,
381                                       &handle);
382     if (!result.isOk()) {
383         printf("Verify: BeginOperation failed: %d\n", int32_t(result));
384         return result;
385     }
386     result = keystore->updateOperation(handle, empty_params, "data_to_sign",
387                                        &num_input_bytes_consumed, &output_params, &output_data);
388     if (!result.isOk()) {
389         printf("Verify: UpdateOperation failed: %d\n", int32_t(result));
390         return result;
391     }
392     result = keystore->finishOperation(handle, empty_params, signature_to_verify, &output_params,
393                                        &output_data);
394     if (result == ErrorCode::VERIFICATION_FAILED) {
395         printf("Verify: Failed to verify signature.\n");
396         return result;
397     }
398     if (!result.isOk()) {
399         printf("Verify: FinishOperation failed: %d\n", int32_t(result));
400         return result;
401     }
402     printf("Verify: OK\n");
403     return 0;
404 }
405 
Encrypt(const std::string & key_name,const std::string & input_filename,const std::string & output_filename)406 int Encrypt(const std::string& key_name, const std::string& input_filename,
407             const std::string& output_filename) {
408     std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance();
409     std::string input = ReadFile(input_filename);
410     std::string output;
411     if (!keystore->encryptWithAuthentication(key_name, input, &output)) {
412         printf("EncryptWithAuthentication failed.\n");
413         return 1;
414     }
415     WriteFile(output_filename, output);
416     return 0;
417 }
418 
Decrypt(const std::string & key_name,const std::string & input_filename,const std::string & output_filename)419 int Decrypt(const std::string& key_name, const std::string& input_filename,
420             const std::string& output_filename) {
421     std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance();
422     std::string input = ReadFile(input_filename);
423     std::string output;
424     if (!keystore->decryptWithAuthentication(key_name, input, &output)) {
425         printf("DecryptWithAuthentication failed.\n");
426         return 1;
427     }
428     WriteFile(output_filename, output);
429     return 0;
430 }
431 
432 }  // namespace
433 
main(int argc,char ** argv)434 int main(int argc, char** argv) {
435     CommandLine::Init(argc, argv);
436     CommandLine* command_line = CommandLine::ForCurrentProcess();
437     CommandLine::StringVector args = command_line->GetArgs();
438     if (args.empty()) {
439         PrintUsageAndExit();
440     }
441     if (args[0] == "brillo-platform-test") {
442         return BrilloPlatformTest(command_line->GetSwitchValueASCII("prefix"),
443                                   command_line->HasSwitch("test_for_0_3"));
444     } else if (args[0] == "list-brillo-tests") {
445         return ListTestCases();
446     } else if (args[0] == "add-entropy") {
447         return AddEntropy(command_line->GetSwitchValueASCII("input"));
448     } else if (args[0] == "generate") {
449         return GenerateKey(command_line->GetSwitchValueASCII("name"));
450     } else if (args[0] == "get-chars") {
451         return GetCharacteristics(command_line->GetSwitchValueASCII("name"));
452     } else if (args[0] == "export") {
453         return ExportKey(command_line->GetSwitchValueASCII("name"));
454     } else if (args[0] == "delete") {
455         return DeleteKey(command_line->GetSwitchValueASCII("name"));
456     } else if (args[0] == "delete-all") {
457         return DeleteAllKeys();
458     } else if (args[0] == "exists") {
459         return DoesKeyExist(command_line->GetSwitchValueASCII("name"));
460     } else if (args[0] == "list") {
461         return List(command_line->GetSwitchValueASCII("prefix"));
462     } else if (args[0] == "sign-verify") {
463         return SignAndVerify(command_line->GetSwitchValueASCII("name"));
464     } else if (args[0] == "encrypt") {
465         return Encrypt(command_line->GetSwitchValueASCII("name"),
466                        command_line->GetSwitchValueASCII("in"),
467                        command_line->GetSwitchValueASCII("out"));
468     } else if (args[0] == "decrypt") {
469         return Decrypt(command_line->GetSwitchValueASCII("name"),
470                        command_line->GetSwitchValueASCII("in"),
471                        command_line->GetSwitchValueASCII("out"));
472     } else {
473         PrintUsageAndExit();
474     }
475     return 0;
476 }
477