blob: 297b505bdd6daebcf27115977676d34507b38d99 [file] [log] [blame]
Jiyong Parka7266ac2021-05-17 21:57:24 +09001/*
2 * Copyright (C) 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 */
Alan Stokesd1a30dd2022-11-30 09:39:54 +000016
Inseob Kim06a64d62021-09-07 21:21:45 +090017#include <aidl/com/android/microdroid/testservice/BnTestService.h>
Alan Stokes63fa37b2023-02-22 14:56:57 +000018#include <aidl/com/android/microdroid/testservice/BnVmCallback.h>
19#include <aidl/com/android/microdroid/testservice/IAppCallback.h>
Inseob Kimdb319702022-01-20 13:12:43 +090020#include <android-base/file.h>
Inseob Kim691df6a2022-01-20 12:54:30 +090021#include <android-base/properties.h>
Andrew Scull11cf0902021-06-22 12:08:10 +000022#include <android-base/result.h>
Nikita Ioffe3452ee22022-12-15 00:31:56 +000023#include <android-base/scopeguard.h>
Alan Stokesd1a30dd2022-11-30 09:39:54 +000024#include <android/log.h>
Inseob Kim06a64d62021-09-07 21:21:45 +090025#include <fcntl.h>
Nikita Ioffe29e15c82023-02-25 02:31:51 +000026#include <fstab/fstab.h>
Inseob Kimdb319702022-01-20 13:12:43 +090027#include <fsverity_digests.pb.h>
Inseob Kim06a64d62021-09-07 21:21:45 +090028#include <linux/vm_sockets.h>
29#include <stdint.h>
Jiyong Parka7266ac2021-05-17 21:57:24 +090030#include <stdio.h>
Nikita Ioffe3452ee22022-12-15 00:31:56 +000031#include <sys/capability.h>
Jiyong Park23934392021-06-16 01:59:10 +090032#include <sys/system_properties.h>
Inseob Kim06a64d62021-09-07 21:21:45 +090033#include <unistd.h>
Alan Stokes52d3c722022-10-04 17:27:13 +010034#include <vm_main.h>
Alan Stokesd4ea5a82022-11-10 12:17:42 +000035#include <vm_payload_restricted.h>
Inseob Kim06a64d62021-09-07 21:21:45 +090036
Inseob Kim691df6a2022-01-20 12:54:30 +090037#include <string>
Alan Stokesd1a30dd2022-11-30 09:39:54 +000038#include <thread>
Jiyong Parka7266ac2021-05-17 21:57:24 +090039
Alan Stokesd1a30dd2022-11-30 09:39:54 +000040using android::base::borrowed_fd;
Inseob Kim06a64d62021-09-07 21:21:45 +090041using android::base::ErrnoError;
Andrew Scull11cf0902021-06-22 12:08:10 +000042using android::base::Error;
Nikita Ioffe3452ee22022-12-15 00:31:56 +000043using android::base::make_scope_guard;
Andrew Scull11cf0902021-06-22 12:08:10 +000044using android::base::Result;
Alan Stokesd1a30dd2022-11-30 09:39:54 +000045using android::base::unique_fd;
Nikita Ioffe29e15c82023-02-25 02:31:51 +000046using android::fs_mgr::Fstab;
47using android::fs_mgr::FstabEntry;
48using android::fs_mgr::GetEntryForMountPoint;
49using android::fs_mgr::ReadFstabFromFile;
Alan Stokesd1a30dd2022-11-30 09:39:54 +000050
51using aidl::com::android::microdroid::testservice::BnTestService;
Alan Stokes63fa37b2023-02-22 14:56:57 +000052using aidl::com::android::microdroid::testservice::BnVmCallback;
53using aidl::com::android::microdroid::testservice::IAppCallback;
Alan Stokesd1a30dd2022-11-30 09:39:54 +000054using ndk::ScopedAStatus;
Andrew Scull66616612021-06-17 16:41:03 +000055
Jiyong Parkfe5b28e2021-06-24 00:19:02 +090056extern void testlib_sub();
57
Andrew Scull66616612021-06-17 16:41:03 +000058namespace {
59
Alan Stokesd1a30dd2022-11-30 09:39:54 +000060constexpr char TAG[] = "testbinary";
61
Andrew Scull11cf0902021-06-22 12:08:10 +000062template <typename T>
Andrew Sculledbe75e2021-07-06 10:44:31 +000063Result<T> report_test(std::string name, Result<T> result) {
Andrew Scull11cf0902021-06-22 12:08:10 +000064 auto property = "debug.microdroid.test." + name;
65 std::stringstream outcome;
66 if (result.ok()) {
67 outcome << "PASS";
68 } else {
69 outcome << "FAIL: " << result.error();
Alan Stokesd1a30dd2022-11-30 09:39:54 +000070 // Log the error in case the property is truncated.
71 std::string message = name + ": " + outcome.str();
72 __android_log_write(ANDROID_LOG_WARN, TAG, message.c_str());
Andrew Scull11cf0902021-06-22 12:08:10 +000073 }
74 __system_property_set(property.c_str(), outcome.str().c_str());
Andrew Sculledbe75e2021-07-06 10:44:31 +000075 return result;
Andrew Scull66616612021-06-17 16:41:03 +000076}
77
Alan Stokesd1a30dd2022-11-30 09:39:54 +000078Result<void> run_echo_reverse_server(borrowed_fd listening_fd) {
79 struct sockaddr_vm client_sa = {};
80 socklen_t client_sa_len = sizeof(client_sa);
81 unique_fd connect_fd{accept4(listening_fd.get(), (struct sockaddr*)&client_sa, &client_sa_len,
82 SOCK_CLOEXEC)};
83 if (!connect_fd.ok()) {
84 return ErrnoError() << "Failed to accept vsock connection";
85 }
86
87 unique_fd input_fd{fcntl(connect_fd, F_DUPFD_CLOEXEC, 0)};
88 if (!input_fd.ok()) {
89 return ErrnoError() << "Failed to dup";
90 }
91 FILE* input = fdopen(input_fd.release(), "r");
92 if (!input) {
93 return ErrnoError() << "Failed to fdopen";
94 }
95
David Brazdilbcce3512023-02-23 15:32:55 +000096 // Run forever, reverse one line at a time.
97 while (true) {
98 char* line = nullptr;
99 size_t size = 0;
100 if (getline(&line, &size, input) < 0) {
101 return ErrnoError() << "Failed to read";
102 }
103
104 std::string_view original = line;
105 if (!original.empty() && original.back() == '\n') {
106 original = original.substr(0, original.size() - 1);
107 }
108
109 std::string reversed(original.rbegin(), original.rend());
110 reversed += "\n";
111
112 if (write(connect_fd, reversed.data(), reversed.size()) < 0) {
113 return ErrnoError() << "Failed to write";
114 }
Alan Stokesd1a30dd2022-11-30 09:39:54 +0000115 }
Alan Stokesd1a30dd2022-11-30 09:39:54 +0000116}
117
118Result<void> start_echo_reverse_server() {
119 unique_fd server_fd{TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC, 0))};
120 if (!server_fd.ok()) {
121 return ErrnoError() << "Failed to create vsock socket";
122 }
123 struct sockaddr_vm server_sa = (struct sockaddr_vm){
124 .svm_family = AF_VSOCK,
Alan Stokes10c47672022-12-13 17:17:08 +0000125 .svm_port = static_cast<uint32_t>(BnTestService::ECHO_REVERSE_PORT),
Alan Stokesd1a30dd2022-11-30 09:39:54 +0000126 .svm_cid = VMADDR_CID_ANY,
127 };
128 int ret = TEMP_FAILURE_RETRY(bind(server_fd, (struct sockaddr*)&server_sa, sizeof(server_sa)));
129 if (ret < 0) {
130 return ErrnoError() << "Failed to bind vsock socket";
131 }
132 ret = TEMP_FAILURE_RETRY(listen(server_fd, /*backlog=*/1));
133 if (ret < 0) {
134 return ErrnoError() << "Failed to listen";
135 }
136
137 std::thread accept_thread{[listening_fd = std::move(server_fd)] {
138 auto result = run_echo_reverse_server(listening_fd);
139 if (!result.ok()) {
140 __android_log_write(ANDROID_LOG_ERROR, TAG, result.error().message().c_str());
141 // Make sure the VM exits so the test will fail solidly
142 exit(1);
143 }
144 }};
145 accept_thread.detach();
146
147 return {};
148}
149
Inseob Kim06a64d62021-09-07 21:21:45 +0900150Result<void> start_test_service() {
Alan Stokes63fa37b2023-02-22 14:56:57 +0000151 class VmCallbackImpl : public BnVmCallback {
152 private:
153 std::shared_ptr<IAppCallback> mAppCallback;
154
155 public:
156 explicit VmCallbackImpl(const std::shared_ptr<IAppCallback>& appCallback)
157 : mAppCallback(appCallback) {}
158
159 ScopedAStatus echoMessage(const std::string& message) override {
160 std::thread callback_thread{[=, appCallback = mAppCallback] {
161 appCallback->onEchoRequestReceived("Received: " + message);
162 }};
163 callback_thread.detach();
164 return ScopedAStatus::ok();
165 }
166 };
167
Alan Stokesd1a30dd2022-11-30 09:39:54 +0000168 class TestService : public BnTestService {
Alan Stokes63fa37b2023-02-22 14:56:57 +0000169 public:
Alan Stokesd1a30dd2022-11-30 09:39:54 +0000170 ScopedAStatus addInteger(int32_t a, int32_t b, int32_t* out) override {
Inseob Kim06a64d62021-09-07 21:21:45 +0900171 *out = a + b;
Alan Stokesd1a30dd2022-11-30 09:39:54 +0000172 return ScopedAStatus::ok();
Inseob Kim06a64d62021-09-07 21:21:45 +0900173 }
Inseob Kim691df6a2022-01-20 12:54:30 +0900174
Alan Stokesd1a30dd2022-11-30 09:39:54 +0000175 ScopedAStatus readProperty(const std::string& prop, std::string* out) override {
Inseob Kim691df6a2022-01-20 12:54:30 +0900176 *out = android::base::GetProperty(prop, "");
177 if (out->empty()) {
178 std::string msg = "cannot find property " + prop;
Alan Stokesd1a30dd2022-11-30 09:39:54 +0000179 return ScopedAStatus::fromExceptionCodeWithMessage(EX_SERVICE_SPECIFIC,
180 msg.c_str());
Inseob Kim691df6a2022-01-20 12:54:30 +0900181 }
182
Alan Stokesd1a30dd2022-11-30 09:39:54 +0000183 return ScopedAStatus::ok();
Inseob Kim691df6a2022-01-20 12:54:30 +0900184 }
Andrew Scull2e6ab792022-01-30 16:04:08 +0000185
Alan Stokesd1a30dd2022-11-30 09:39:54 +0000186 ScopedAStatus insecurelyExposeVmInstanceSecret(std::vector<uint8_t>* out) override {
Andrew Scull102067a2022-10-07 00:34:40 +0000187 const uint8_t identifier[] = {1, 2, 3, 4};
Andrew Scull655e98e2022-10-10 22:24:58 +0000188 out->resize(32);
Alan Stokes65bbb912022-11-23 09:39:34 +0000189 AVmPayload_getVmInstanceSecret(identifier, sizeof(identifier), out->data(),
190 out->size());
Alan Stokesd1a30dd2022-11-30 09:39:54 +0000191 return ScopedAStatus::ok();
Andrew Scull2e6ab792022-01-30 16:04:08 +0000192 }
Andrew Scull1f6ca352022-02-20 22:51:12 +0000193
Alan Stokesd1a30dd2022-11-30 09:39:54 +0000194 ScopedAStatus insecurelyExposeAttestationCdi(std::vector<uint8_t>* out) override {
Alan Stokes65bbb912022-11-23 09:39:34 +0000195 size_t cdi_size = AVmPayload_getDiceAttestationCdi(nullptr, 0);
Andrew Scull655e98e2022-10-10 22:24:58 +0000196 out->resize(cdi_size);
Alan Stokes65bbb912022-11-23 09:39:34 +0000197 AVmPayload_getDiceAttestationCdi(out->data(), out->size());
Alan Stokesd1a30dd2022-11-30 09:39:54 +0000198 return ScopedAStatus::ok();
Andrew Scull1f6ca352022-02-20 22:51:12 +0000199 }
Andrew Scull61892082022-02-21 00:07:25 +0000200
Alan Stokesd1a30dd2022-11-30 09:39:54 +0000201 ScopedAStatus getBcc(std::vector<uint8_t>* out) override {
Alan Stokes65bbb912022-11-23 09:39:34 +0000202 size_t bcc_size = AVmPayload_getDiceAttestationChain(nullptr, 0);
Andrew Scull655e98e2022-10-10 22:24:58 +0000203 out->resize(bcc_size);
Alan Stokes65bbb912022-11-23 09:39:34 +0000204 AVmPayload_getDiceAttestationChain(out->data(), out->size());
Alan Stokesd1a30dd2022-11-30 09:39:54 +0000205 return ScopedAStatus::ok();
Andrew Scull61892082022-02-21 00:07:25 +0000206 }
Alice Wang6bbb6da2022-10-26 12:44:06 +0000207
Alan Stokesd1a30dd2022-11-30 09:39:54 +0000208 ScopedAStatus getApkContentsPath(std::string* out) override {
Alice Wang6bbb6da2022-10-26 12:44:06 +0000209 const char* path_c = AVmPayload_getApkContentsPath();
210 if (path_c == nullptr) {
Alan Stokesd1a30dd2022-11-30 09:39:54 +0000211 return ScopedAStatus::
Alice Wang6bbb6da2022-10-26 12:44:06 +0000212 fromServiceSpecificErrorWithMessage(0, "Failed to get APK contents path");
213 }
Alan Stokesd1a30dd2022-11-30 09:39:54 +0000214 *out = path_c;
215 return ScopedAStatus::ok();
Alice Wang6bbb6da2022-10-26 12:44:06 +0000216 }
Alan Stokes78d24702022-11-21 15:28:31 +0000217
Alan Stokesd1a30dd2022-11-30 09:39:54 +0000218 ScopedAStatus getEncryptedStoragePath(std::string* out) override {
Alan Stokes78d24702022-11-21 15:28:31 +0000219 const char* path_c = AVmPayload_getEncryptedStoragePath();
220 if (path_c == nullptr) {
221 out->clear();
222 } else {
223 *out = path_c;
224 }
Alan Stokesd1a30dd2022-11-30 09:39:54 +0000225 return ScopedAStatus::ok();
226 }
227
Nikita Ioffe3452ee22022-12-15 00:31:56 +0000228 ScopedAStatus getEffectiveCapabilities(std::vector<std::string>* out) override {
229 if (out == nullptr) {
230 return ScopedAStatus::ok();
231 }
232 cap_t cap = cap_get_proc();
233 auto guard = make_scope_guard([&cap]() { cap_free(cap); });
234 for (cap_value_t cap_id = 0; cap_id < CAP_LAST_CAP + 1; cap_id++) {
235 cap_flag_value_t value;
236 if (cap_get_flag(cap, cap_id, CAP_EFFECTIVE, &value) != 0) {
237 return ScopedAStatus::
238 fromServiceSpecificErrorWithMessage(0, "cap_get_flag failed");
239 }
240 if (value == CAP_SET) {
241 // Ideally we would just send back the cap_ids, but I wasn't able to find java
242 // APIs for linux capabilities, hence we transform to the human readable name
243 // here.
244 char* name = cap_to_name(cap_id);
245 out->push_back(std::string(name) + "(" + std::to_string(cap_id) + ")");
246 }
247 }
248 return ScopedAStatus::ok();
249 }
250
Alan Stokes63fa37b2023-02-22 14:56:57 +0000251 ScopedAStatus runEchoReverseServer() override {
Alan Stokesd1a30dd2022-11-30 09:39:54 +0000252 auto result = start_echo_reverse_server();
253 if (result.ok()) {
254 return ScopedAStatus::ok();
255 } else {
256 std::string message = result.error().message();
257 return ScopedAStatus::fromServiceSpecificErrorWithMessage(-1, message.c_str());
258 }
Alan Stokes78d24702022-11-21 15:28:31 +0000259 }
Shikha Panwardc11b7e2022-12-15 12:24:11 +0000260
261 ScopedAStatus writeToFile(const std::string& content, const std::string& path) override {
262 if (!android::base::WriteStringToFile(content, path)) {
263 std::string msg = "Failed to write " + content + " to file " + path +
264 ". Errono: " + std::to_string(errno);
265 return ScopedAStatus::fromExceptionCodeWithMessage(EX_SERVICE_SPECIFIC,
266 msg.c_str());
267 }
Shikha Panwardc11b7e2022-12-15 12:24:11 +0000268 return ScopedAStatus::ok();
269 }
270
271 ScopedAStatus readFromFile(const std::string& path, std::string* out) override {
272 if (!android::base::ReadFileToString(path, out)) {
273 std::string msg =
274 "Failed to read " + path + " to string. Errono: " + std::to_string(errno);
275 return ScopedAStatus::fromExceptionCodeWithMessage(EX_SERVICE_SPECIFIC,
276 msg.c_str());
277 }
278 return ScopedAStatus::ok();
279 }
Shikha Panwardef7ef92023-01-06 08:35:48 +0000280
Nikita Ioffea7cb3672023-02-24 23:10:34 +0000281 ScopedAStatus getFilePermissions(const std::string& path, int32_t* out) override {
282 struct stat sb;
283 if (stat(path.c_str(), &sb) != -1) {
284 *out = sb.st_mode;
285 } else {
286 std::string msg = "stat " + path + " failed : " + std::strerror(errno);
287 return ScopedAStatus::fromExceptionCodeWithMessage(EX_SERVICE_SPECIFIC,
288 msg.c_str());
289 }
290 return ScopedAStatus::ok();
291 }
292
Nikita Ioffe29e15c82023-02-25 02:31:51 +0000293 ScopedAStatus getMountFlags(const std::string& mount_point, int32_t* out) override {
294 Fstab fstab;
295 if (!ReadFstabFromFile("/proc/mounts", &fstab)) {
296 return ScopedAStatus::fromExceptionCodeWithMessage(EX_SERVICE_SPECIFIC,
297 "Failed to read /proc/mounts");
298 }
299 FstabEntry* entry = GetEntryForMountPoint(&fstab, mount_point);
300 if (entry == nullptr) {
301 std::string msg = mount_point + " not found in /proc/mounts";
302 return ScopedAStatus::fromExceptionCodeWithMessage(EX_SERVICE_SPECIFIC,
303 msg.c_str());
304 }
305 *out = entry->flags;
306 return ScopedAStatus::ok();
307 }
308
Alan Stokes63fa37b2023-02-22 14:56:57 +0000309 ScopedAStatus requestCallback(const std::shared_ptr<IAppCallback>& appCallback) {
310 auto vmCallback = ndk::SharedRefBase::make<VmCallbackImpl>(appCallback);
311 std::thread callback_thread{[=] { appCallback->setVmCallback(vmCallback); }};
312 callback_thread.detach();
313 return ScopedAStatus::ok();
314 }
315
Jiyong Park92e34722023-06-27 00:43:39 +0900316 ScopedAStatus readLineFromConsole(std::string* out) {
317 FILE* f = fopen("/dev/console", "r");
318 if (f == nullptr) {
319 return ScopedAStatus::fromExceptionCodeWithMessage(EX_SERVICE_SPECIFIC,
320 "failed to open /dev/console");
321 }
322 char* line = nullptr;
323 size_t len = 0;
324 ssize_t nread = getline(&line, &len, f);
325
326 if (nread == -1) {
327 free(line);
328 return ScopedAStatus::fromExceptionCodeWithMessage(EX_SERVICE_SPECIFIC,
329 "failed to read /dev/console");
330 }
331 out->append(line, nread);
332 free(line);
333 return ScopedAStatus::ok();
334 }
335
Shikha Panwardef7ef92023-01-06 08:35:48 +0000336 ScopedAStatus quit() override { exit(0); }
Inseob Kim06a64d62021-09-07 21:21:45 +0900337 };
338 auto testService = ndk::SharedRefBase::make<TestService>();
339
Alan Stokes65bbb912022-11-23 09:39:34 +0000340 auto callback = []([[maybe_unused]] void* param) { AVmPayload_notifyPayloadReady(); };
Devin Moorecaf7b952023-04-24 20:14:35 +0000341 AVmPayload_runVsockRpcServer(testService->asBinder().get(), testService->PORT, callback,
Alan Stokese0945ad2022-11-24 13:29:57 +0000342 nullptr);
Inseob Kim06a64d62021-09-07 21:21:45 +0900343
344 return {};
345}
346
Inseob Kimdb319702022-01-20 13:12:43 +0900347Result<void> verify_apk() {
348 const char* path = "/mnt/extra-apk/0/assets/build_manifest.pb";
349
350 std::string str;
351 if (!android::base::ReadFileToString(path, &str)) {
352 return ErrnoError() << "failed to read build_manifest.pb";
353 }
354
355 if (!android::security::fsverity::FSVerityDigests().ParseFromString(str)) {
356 return Error() << "invalid build_manifest.pb";
357 }
358
359 return {};
360}
361
Andrew Scull66616612021-06-17 16:41:03 +0000362} // Anonymous namespace
363
Alan Stokes52d3c722022-10-04 17:27:13 +0100364extern "C" int AVmPayload_main() {
Alan Stokesd1a30dd2022-11-30 09:39:54 +0000365 __android_log_write(ANDROID_LOG_INFO, TAG, "Hello Microdroid");
Inseob Kim06a64d62021-09-07 21:21:45 +0900366
Alan Stokesd1a30dd2022-11-30 09:39:54 +0000367 // Make sure we can call into other shared libraries.
Jiyong Parkfe5b28e2021-06-24 00:19:02 +0900368 testlib_sub();
Jiyong Park23934392021-06-16 01:59:10 +0900369
Inseob Kimdb319702022-01-20 13:12:43 +0900370 // Extra apks may be missing; this is not a fatal error
371 report_test("extra_apk", verify_apk());
372
Jiyong Park23934392021-06-16 01:59:10 +0900373 __system_property_set("debug.microdroid.app.run", "true");
Andrew Sculledbe75e2021-07-06 10:44:31 +0000374
Inseob Kim06a64d62021-09-07 21:21:45 +0900375 if (auto res = start_test_service(); res.ok()) {
376 return 0;
377 } else {
Alan Stokesd1a30dd2022-11-30 09:39:54 +0000378 __android_log_write(ANDROID_LOG_ERROR, TAG, res.error().message().c_str());
Inseob Kim06a64d62021-09-07 21:21:45 +0900379 return 1;
380 }
Jiyong Parka7266ac2021-05-17 21:57:24 +0900381}