blob: c29bacbe0a72ae5c04c4b15cbe66b92189c51a0d [file] [log] [blame]
Max Biresf60987e2021-04-16 13:35:20 -07001/*
2 * Copyright 2021 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 <string>
18#include <vector>
19
20#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
21#include <android/binder_manager.h>
22#include <cppbor.h>
Seth Moore01688562021-06-22 12:59:32 -070023#include <gflags/gflags.h>
Max Biresf60987e2021-04-16 13:35:20 -070024#include <keymaster/cppcose/cppcose.h>
Seth Moore9a4bc972021-07-22 16:46:07 -070025#include <openssl/base64.h>
Seth Moore6dfb02a2021-06-18 15:43:09 -070026#include <remote_prov/remote_prov_utils.h>
Seth Moore5a40fa72021-06-22 13:48:59 -070027#include <sys/random.h>
Max Biresf60987e2021-04-16 13:35:20 -070028
29using aidl::android::hardware::security::keymint::DeviceInfo;
30using aidl::android::hardware::security::keymint::IRemotelyProvisionedComponent;
31using aidl::android::hardware::security::keymint::MacedPublicKey;
32using aidl::android::hardware::security::keymint::ProtectedData;
Max Biresd0f7b352022-01-27 18:30:46 -080033using aidl::android::hardware::security::keymint::RpcHardwareInfo;
Seth Moore6dfb02a2021-06-18 15:43:09 -070034using aidl::android::hardware::security::keymint::remote_prov::generateEekChain;
Seth Moore01688562021-06-22 12:59:32 -070035using aidl::android::hardware::security::keymint::remote_prov::getProdEekChain;
Seth Mooree44aad22021-06-25 17:38:24 -070036using aidl::android::hardware::security::keymint::remote_prov::jsonEncodeCsrWithBuild;
Max Biresf60987e2021-04-16 13:35:20 -070037
Max Biresf60987e2021-04-16 13:35:20 -070038using namespace cppbor;
39using namespace cppcose;
40
Seth Moore01688562021-06-22 12:59:32 -070041DEFINE_bool(test_mode, false, "If enabled, a fake EEK key/cert are used.");
42
Seth Mooree44aad22021-06-25 17:38:24 -070043DEFINE_string(output_format, "csr", "How to format the output. Defaults to 'csr'.");
44
Max Biresf60987e2021-04-16 13:35:20 -070045namespace {
46
Seth Mooree44aad22021-06-25 17:38:24 -070047// Various supported --output_format values.
48constexpr std::string_view kBinaryCsrOutput = "csr"; // Just the raw csr as binary
49constexpr std::string_view kBuildPlusCsr = "build+csr"; // Text-encoded (JSON) build
50 // fingerprint plus CSR.
51
Seth Moore5a40fa72021-06-22 13:48:59 -070052constexpr size_t kChallengeSize = 16;
53
Seth Moore9a4bc972021-07-22 16:46:07 -070054std::string toBase64(const std::vector<uint8_t>& buffer) {
55 size_t base64Length;
56 int rc = EVP_EncodedLength(&base64Length, buffer.size());
57 if (!rc) {
58 std::cerr << "Error getting base64 length. Size overflow?" << std::endl;
59 exit(-1);
60 }
61
62 std::string base64(base64Length, ' ');
63 rc = EVP_EncodeBlock(reinterpret_cast<uint8_t*>(base64.data()), buffer.data(), buffer.size());
64 ++rc; // Account for NUL, which BoringSSL does not for some reason.
65 if (rc != base64Length) {
66 std::cerr << "Error writing base64. Expected " << base64Length
67 << " bytes to be written, but " << rc << " bytes were actually written."
68 << std::endl;
69 exit(-1);
70 }
71 return base64;
72}
73
Seth Moore5a40fa72021-06-22 13:48:59 -070074std::vector<uint8_t> generateChallenge() {
75 std::vector<uint8_t> challenge(kChallengeSize);
76
77 ssize_t bytesRemaining = static_cast<ssize_t>(challenge.size());
78 uint8_t* writePtr = challenge.data();
79 while (bytesRemaining > 0) {
80 int bytesRead = getrandom(writePtr, bytesRemaining, /*flags=*/0);
Keith Mokb9462c12021-11-11 19:34:26 +000081 if (bytesRead < 0) {
82 if (errno == EINTR) {
83 continue;
84 } else {
85 std::cerr << errno << ": " << strerror(errno) << std::endl;
86 exit(-1);
87 }
Seth Moore5a40fa72021-06-22 13:48:59 -070088 }
89 bytesRemaining -= bytesRead;
90 writePtr += bytesRead;
91 }
92
93 return challenge;
Max Biresf60987e2021-04-16 13:35:20 -070094}
95
Seth Moore9ea08f22021-07-22 16:42:17 -070096Array composeCertificateRequest(const ProtectedData& protectedData,
97 const DeviceInfo& verifiedDeviceInfo,
98 const std::vector<uint8_t>& challenge,
99 const std::vector<uint8_t>& keysToSignMac) {
100 Array macedKeysToSign = Array()
101 .add(std::vector<uint8_t>(0)) // empty protected headers as bstr
102 .add(Map()) // empty unprotected headers
103 .add(Null()) // nil for the payload
104 .add(keysToSignMac); // MAC as returned from the HAL
105
106 Array deviceInfo =
107 Array().add(EncodedItem(verifiedDeviceInfo.deviceInfo)).add(Map()); // Empty device info
108
109 Array certificateRequest = Array()
110 .add(std::move(deviceInfo))
111 .add(challenge)
112 .add(EncodedItem(protectedData.protectedData))
113 .add(std::move(macedKeysToSign));
Seth Mooree44aad22021-06-25 17:38:24 -0700114 return certificateRequest;
Max Biresf60987e2021-04-16 13:35:20 -0700115}
116
Max Biresd0f7b352022-01-27 18:30:46 -0800117std::vector<uint8_t> getEekChain(uint32_t curve) {
Seth Moore01688562021-06-22 12:59:32 -0700118 if (FLAGS_test_mode) {
119 const std::vector<uint8_t> kFakeEekId = {'f', 'a', 'k', 'e', 0};
Max Biresd0f7b352022-01-27 18:30:46 -0800120 auto eekOrErr = generateEekChain(curve, 3 /* chainlength */, kFakeEekId);
Seth Moore59146252021-07-02 08:59:23 -0700121 if (!eekOrErr) {
122 std::cerr << "Failed to generate test EEK somehow: " << eekOrErr.message() << std::endl;
123 exit(-1);
124 }
Seth Moore9a4bc972021-07-22 16:46:07 -0700125 auto [eek, pubkey, privkey] = eekOrErr.moveValue();
126 std::cout << "EEK raw keypair:" << std::endl;
127 std::cout << " pub: " << toBase64(pubkey) << std::endl;
128 std::cout << " priv: " << toBase64(privkey) << std::endl;
Seth Moore01688562021-06-22 12:59:32 -0700129 return eek;
130 }
131
Max Biresd0f7b352022-01-27 18:30:46 -0800132 return getProdEekChain(curve);
Seth Moore01688562021-06-22 12:59:32 -0700133}
134
Seth Mooree44aad22021-06-25 17:38:24 -0700135void writeOutput(const Array& csr) {
136 if (FLAGS_output_format == kBinaryCsrOutput) {
137 auto bytes = csr.encode();
138 std::copy(bytes.begin(), bytes.end(), std::ostream_iterator<char>(std::cout));
139 } else if (FLAGS_output_format == kBuildPlusCsr) {
140 auto [json, error] = jsonEncodeCsrWithBuild(csr);
141 if (!error.empty()) {
142 std::cerr << "Error JSON encoding the output: " << error;
143 exit(1);
144 }
145 std::cout << json << std::endl;
146 } else {
147 std::cerr << "Unexpected output_format '" << FLAGS_output_format << "'" << std::endl;
148 std::cerr << "Valid formats:" << std::endl;
149 std::cerr << " " << kBinaryCsrOutput << std::endl;
150 std::cerr << " " << kBuildPlusCsr << std::endl;
151 exit(1);
152 }
153}
154
Seth Moore59146252021-07-02 08:59:23 -0700155// Callback for AServiceManager_forEachDeclaredInstance that writes out a CSR
156// for every IRemotelyProvisionedComponent.
157void getCsrForInstance(const char* name, void* /*context*/) {
158 const std::vector<uint8_t> challenge = generateChallenge();
159
160 auto fullName = std::string(IRemotelyProvisionedComponent::descriptor) + "/" + name;
161 AIBinder* rkpAiBinder = AServiceManager_getService(fullName.c_str());
162 ::ndk::SpAIBinder rkp_binder(rkpAiBinder);
163 auto rkp_service = IRemotelyProvisionedComponent::fromBinder(rkp_binder);
164 if (!rkp_service) {
165 std::cerr << "Unable to get binder object for '" << fullName << "', skipping.";
Keith Mokb9462c12021-11-11 19:34:26 +0000166 exit(-1);
Seth Moore59146252021-07-02 08:59:23 -0700167 }
168
169 std::vector<uint8_t> keysToSignMac;
170 std::vector<MacedPublicKey> emptyKeys;
Seth Moore9ea08f22021-07-22 16:42:17 -0700171 DeviceInfo verifiedDeviceInfo;
Seth Moore59146252021-07-02 08:59:23 -0700172 ProtectedData protectedData;
Max Biresd0f7b352022-01-27 18:30:46 -0800173 RpcHardwareInfo hwInfo;
174 ::ndk::ScopedAStatus status = rkp_service->getHardwareInfo(&hwInfo);
175 if (!status.isOk()) {
176 std::cerr << "Failed to get hardware info for '" << fullName
177 << "'. Error code: " << status.getServiceSpecificError() << "." << std::endl;
178 exit(-1);
179 }
180 status = rkp_service->generateCertificateRequest(
181 FLAGS_test_mode, emptyKeys, getEekChain(hwInfo.supportedEekCurve), challenge,
182 &verifiedDeviceInfo, &protectedData, &keysToSignMac);
Seth Moore59146252021-07-02 08:59:23 -0700183 if (!status.isOk()) {
184 std::cerr << "Bundle extraction failed for '" << fullName
185 << "'. Error code: " << status.getServiceSpecificError() << "." << std::endl;
186 exit(-1);
187 }
Seth Moore9ea08f22021-07-22 16:42:17 -0700188 auto request =
189 composeCertificateRequest(protectedData, verifiedDeviceInfo, challenge, keysToSignMac);
190 writeOutput(request);
Seth Moore59146252021-07-02 08:59:23 -0700191}
192
Max Biresf60987e2021-04-16 13:35:20 -0700193} // namespace
194
Seth Moore01688562021-06-22 12:59:32 -0700195int main(int argc, char** argv) {
196 gflags::ParseCommandLineFlags(&argc, &argv, /*remove_flags=*/true);
197
Seth Moore59146252021-07-02 08:59:23 -0700198 AServiceManager_forEachDeclaredInstance(IRemotelyProvisionedComponent::descriptor,
199 /*context=*/nullptr, getCsrForInstance);
Seth Moore01688562021-06-22 12:59:32 -0700200
Seth Moore59146252021-07-02 08:59:23 -0700201 return 0;
Max Biresf60987e2021-04-16 13:35:20 -0700202}