blob: 9786c3d11a071d410e26b0ae0c560ee713cabeed [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;
Seth Moore6dfb02a2021-06-18 15:43:09 -070033using aidl::android::hardware::security::keymint::remote_prov::generateEekChain;
Seth Moore01688562021-06-22 12:59:32 -070034using aidl::android::hardware::security::keymint::remote_prov::getProdEekChain;
Seth Mooree44aad22021-06-25 17:38:24 -070035using aidl::android::hardware::security::keymint::remote_prov::jsonEncodeCsrWithBuild;
Max Biresf60987e2021-04-16 13:35:20 -070036
Max Biresf60987e2021-04-16 13:35:20 -070037using namespace cppbor;
38using namespace cppcose;
39
Seth Moore01688562021-06-22 12:59:32 -070040DEFINE_bool(test_mode, false, "If enabled, a fake EEK key/cert are used.");
41
Seth Mooree44aad22021-06-25 17:38:24 -070042DEFINE_string(output_format, "csr", "How to format the output. Defaults to 'csr'.");
43
Max Biresf60987e2021-04-16 13:35:20 -070044namespace {
45
Seth Mooree44aad22021-06-25 17:38:24 -070046// Various supported --output_format values.
47constexpr std::string_view kBinaryCsrOutput = "csr"; // Just the raw csr as binary
48constexpr std::string_view kBuildPlusCsr = "build+csr"; // Text-encoded (JSON) build
49 // fingerprint plus CSR.
50
Seth Moore5a40fa72021-06-22 13:48:59 -070051constexpr size_t kChallengeSize = 16;
52
Seth Moore9a4bc972021-07-22 16:46:07 -070053std::string toBase64(const std::vector<uint8_t>& buffer) {
54 size_t base64Length;
55 int rc = EVP_EncodedLength(&base64Length, buffer.size());
56 if (!rc) {
57 std::cerr << "Error getting base64 length. Size overflow?" << std::endl;
58 exit(-1);
59 }
60
61 std::string base64(base64Length, ' ');
62 rc = EVP_EncodeBlock(reinterpret_cast<uint8_t*>(base64.data()), buffer.data(), buffer.size());
63 ++rc; // Account for NUL, which BoringSSL does not for some reason.
64 if (rc != base64Length) {
65 std::cerr << "Error writing base64. Expected " << base64Length
66 << " bytes to be written, but " << rc << " bytes were actually written."
67 << std::endl;
68 exit(-1);
69 }
70 return base64;
71}
72
Seth Moore5a40fa72021-06-22 13:48:59 -070073std::vector<uint8_t> generateChallenge() {
74 std::vector<uint8_t> challenge(kChallengeSize);
75
76 ssize_t bytesRemaining = static_cast<ssize_t>(challenge.size());
77 uint8_t* writePtr = challenge.data();
78 while (bytesRemaining > 0) {
79 int bytesRead = getrandom(writePtr, bytesRemaining, /*flags=*/0);
Keith Mokb9462c12021-11-11 19:34:26 +000080 if (bytesRead < 0) {
81 if (errno == EINTR) {
82 continue;
83 } else {
84 std::cerr << errno << ": " << strerror(errno) << std::endl;
85 exit(-1);
86 }
Seth Moore5a40fa72021-06-22 13:48:59 -070087 }
88 bytesRemaining -= bytesRead;
89 writePtr += bytesRead;
90 }
91
92 return challenge;
Max Biresf60987e2021-04-16 13:35:20 -070093}
94
Seth Moore9ea08f22021-07-22 16:42:17 -070095Array composeCertificateRequest(const ProtectedData& protectedData,
96 const DeviceInfo& verifiedDeviceInfo,
97 const std::vector<uint8_t>& challenge,
98 const std::vector<uint8_t>& keysToSignMac) {
99 Array macedKeysToSign = Array()
100 .add(std::vector<uint8_t>(0)) // empty protected headers as bstr
101 .add(Map()) // empty unprotected headers
102 .add(Null()) // nil for the payload
103 .add(keysToSignMac); // MAC as returned from the HAL
104
105 Array deviceInfo =
106 Array().add(EncodedItem(verifiedDeviceInfo.deviceInfo)).add(Map()); // Empty device info
107
108 Array certificateRequest = Array()
109 .add(std::move(deviceInfo))
110 .add(challenge)
111 .add(EncodedItem(protectedData.protectedData))
112 .add(std::move(macedKeysToSign));
Seth Mooree44aad22021-06-25 17:38:24 -0700113 return certificateRequest;
Max Biresf60987e2021-04-16 13:35:20 -0700114}
115
Seth Moore01688562021-06-22 12:59:32 -0700116std::vector<uint8_t> getEekChain() {
117 if (FLAGS_test_mode) {
118 const std::vector<uint8_t> kFakeEekId = {'f', 'a', 'k', 'e', 0};
119 auto eekOrErr = generateEekChain(3 /* chainlength */, kFakeEekId);
Seth Moore59146252021-07-02 08:59:23 -0700120 if (!eekOrErr) {
121 std::cerr << "Failed to generate test EEK somehow: " << eekOrErr.message() << std::endl;
122 exit(-1);
123 }
Seth Moore9a4bc972021-07-22 16:46:07 -0700124 auto [eek, pubkey, privkey] = eekOrErr.moveValue();
125 std::cout << "EEK raw keypair:" << std::endl;
126 std::cout << " pub: " << toBase64(pubkey) << std::endl;
127 std::cout << " priv: " << toBase64(privkey) << std::endl;
Seth Moore01688562021-06-22 12:59:32 -0700128 return eek;
129 }
130
131 return getProdEekChain();
132}
133
Seth Mooree44aad22021-06-25 17:38:24 -0700134void writeOutput(const Array& csr) {
135 if (FLAGS_output_format == kBinaryCsrOutput) {
136 auto bytes = csr.encode();
137 std::copy(bytes.begin(), bytes.end(), std::ostream_iterator<char>(std::cout));
138 } else if (FLAGS_output_format == kBuildPlusCsr) {
139 auto [json, error] = jsonEncodeCsrWithBuild(csr);
140 if (!error.empty()) {
141 std::cerr << "Error JSON encoding the output: " << error;
142 exit(1);
143 }
144 std::cout << json << std::endl;
145 } else {
146 std::cerr << "Unexpected output_format '" << FLAGS_output_format << "'" << std::endl;
147 std::cerr << "Valid formats:" << std::endl;
148 std::cerr << " " << kBinaryCsrOutput << std::endl;
149 std::cerr << " " << kBuildPlusCsr << std::endl;
150 exit(1);
151 }
152}
153
Seth Moore59146252021-07-02 08:59:23 -0700154// Callback for AServiceManager_forEachDeclaredInstance that writes out a CSR
155// for every IRemotelyProvisionedComponent.
156void getCsrForInstance(const char* name, void* /*context*/) {
157 const std::vector<uint8_t> challenge = generateChallenge();
158
159 auto fullName = std::string(IRemotelyProvisionedComponent::descriptor) + "/" + name;
160 AIBinder* rkpAiBinder = AServiceManager_getService(fullName.c_str());
161 ::ndk::SpAIBinder rkp_binder(rkpAiBinder);
162 auto rkp_service = IRemotelyProvisionedComponent::fromBinder(rkp_binder);
163 if (!rkp_service) {
164 std::cerr << "Unable to get binder object for '" << fullName << "', skipping.";
Keith Mokb9462c12021-11-11 19:34:26 +0000165 exit(-1);
Seth Moore59146252021-07-02 08:59:23 -0700166 }
167
168 std::vector<uint8_t> keysToSignMac;
169 std::vector<MacedPublicKey> emptyKeys;
Seth Moore9ea08f22021-07-22 16:42:17 -0700170 DeviceInfo verifiedDeviceInfo;
Seth Moore59146252021-07-02 08:59:23 -0700171 ProtectedData protectedData;
172 ::ndk::ScopedAStatus status = rkp_service->generateCertificateRequest(
Seth Moore9ea08f22021-07-22 16:42:17 -0700173 FLAGS_test_mode, emptyKeys, getEekChain(), challenge, &verifiedDeviceInfo, &protectedData,
Seth Moore59146252021-07-02 08:59:23 -0700174 &keysToSignMac);
175 if (!status.isOk()) {
176 std::cerr << "Bundle extraction failed for '" << fullName
177 << "'. Error code: " << status.getServiceSpecificError() << "." << std::endl;
178 exit(-1);
179 }
Seth Moore9ea08f22021-07-22 16:42:17 -0700180 auto request =
181 composeCertificateRequest(protectedData, verifiedDeviceInfo, challenge, keysToSignMac);
182 writeOutput(request);
Seth Moore59146252021-07-02 08:59:23 -0700183}
184
Max Biresf60987e2021-04-16 13:35:20 -0700185} // namespace
186
Seth Moore01688562021-06-22 12:59:32 -0700187int main(int argc, char** argv) {
188 gflags::ParseCommandLineFlags(&argc, &argv, /*remove_flags=*/true);
189
Seth Moore59146252021-07-02 08:59:23 -0700190 AServiceManager_forEachDeclaredInstance(IRemotelyProvisionedComponent::descriptor,
191 /*context=*/nullptr, getCsrForInstance);
Seth Moore01688562021-06-22 12:59:32 -0700192
Seth Moore59146252021-07-02 08:59:23 -0700193 return 0;
Max Biresf60987e2021-04-16 13:35:20 -0700194}