1 /*
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  */
16 
17 #include <aidl/com/android/microdroid/testservice/BnTestService.h>
18 #include <aidl/com/android/microdroid/testservice/BnVmCallback.h>
19 #include <aidl/com/android/microdroid/testservice/IAppCallback.h>
20 #include <android-base/file.h>
21 #include <android-base/properties.h>
22 #include <android-base/result.h>
23 #include <android-base/scopeguard.h>
24 #include <android/log.h>
25 #include <fcntl.h>
26 #include <fstab/fstab.h>
27 #include <fsverity_digests.pb.h>
28 #include <linux/vm_sockets.h>
29 #include <stdint.h>
30 #include <stdio.h>
31 #include <sys/capability.h>
32 #include <sys/system_properties.h>
33 #include <unistd.h>
34 #include <vm_main.h>
35 #include <vm_payload_restricted.h>
36 
37 #include <cstdint>
38 #include <string>
39 #include <thread>
40 
41 using android::base::borrowed_fd;
42 using android::base::ErrnoError;
43 using android::base::Error;
44 using android::base::make_scope_guard;
45 using android::base::Result;
46 using android::base::unique_fd;
47 using android::fs_mgr::Fstab;
48 using android::fs_mgr::FstabEntry;
49 using android::fs_mgr::GetEntryForMountPoint;
50 using android::fs_mgr::ReadFstabFromFile;
51 
52 using aidl::com::android::microdroid::testservice::BnTestService;
53 using aidl::com::android::microdroid::testservice::BnVmCallback;
54 using aidl::com::android::microdroid::testservice::IAppCallback;
55 using ndk::ScopedAStatus;
56 
57 extern void testlib_sub();
58 
59 namespace {
60 
61 constexpr char TAG[] = "testbinary";
62 
63 template <typename T>
report_test(std::string name,Result<T> result)64 Result<T> report_test(std::string name, Result<T> result) {
65     auto property = "debug.microdroid.test." + name;
66     std::stringstream outcome;
67     if (result.ok()) {
68         outcome << "PASS";
69     } else {
70         outcome << "FAIL: " << result.error();
71         // Log the error in case the property is truncated.
72         std::string message = name + ": " + outcome.str();
73         __android_log_write(ANDROID_LOG_WARN, TAG, message.c_str());
74     }
75     __system_property_set(property.c_str(), outcome.str().c_str());
76     return result;
77 }
78 
run_echo_reverse_server(borrowed_fd listening_fd)79 Result<void> run_echo_reverse_server(borrowed_fd listening_fd) {
80     struct sockaddr_vm client_sa = {};
81     socklen_t client_sa_len = sizeof(client_sa);
82     unique_fd connect_fd{accept4(listening_fd.get(), (struct sockaddr*)&client_sa, &client_sa_len,
83                                  SOCK_CLOEXEC)};
84     if (!connect_fd.ok()) {
85         return ErrnoError() << "Failed to accept vsock connection";
86     }
87 
88     unique_fd input_fd{fcntl(connect_fd, F_DUPFD_CLOEXEC, 0)};
89     if (!input_fd.ok()) {
90         return ErrnoError() << "Failed to dup";
91     }
92     FILE* input = fdopen(input_fd.release(), "r");
93     if (!input) {
94         return ErrnoError() << "Failed to fdopen";
95     }
96 
97     // Run forever, reverse one line at a time.
98     while (true) {
99         char* line = nullptr;
100         size_t size = 0;
101         if (getline(&line, &size, input) < 0) {
102             return ErrnoError() << "Failed to read";
103         }
104 
105         std::string_view original = line;
106         if (!original.empty() && original.back() == '\n') {
107             original = original.substr(0, original.size() - 1);
108         }
109 
110         std::string reversed(original.rbegin(), original.rend());
111         reversed += "\n";
112 
113         if (write(connect_fd, reversed.data(), reversed.size()) < 0) {
114             return ErrnoError() << "Failed to write";
115         }
116     }
117 }
118 
start_echo_reverse_server()119 Result<void> start_echo_reverse_server() {
120     unique_fd server_fd{TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC, 0))};
121     if (!server_fd.ok()) {
122         return ErrnoError() << "Failed to create vsock socket";
123     }
124     struct sockaddr_vm server_sa = (struct sockaddr_vm){
125             .svm_family = AF_VSOCK,
126             .svm_port = static_cast<uint32_t>(BnTestService::ECHO_REVERSE_PORT),
127             .svm_cid = VMADDR_CID_ANY,
128     };
129     int ret = TEMP_FAILURE_RETRY(bind(server_fd, (struct sockaddr*)&server_sa, sizeof(server_sa)));
130     if (ret < 0) {
131         return ErrnoError() << "Failed to bind vsock socket";
132     }
133     ret = TEMP_FAILURE_RETRY(listen(server_fd, /*backlog=*/1));
134     if (ret < 0) {
135         return ErrnoError() << "Failed to listen";
136     }
137 
138     std::thread accept_thread{[listening_fd = std::move(server_fd)] {
139         auto result = run_echo_reverse_server(listening_fd);
140         if (!result.ok()) {
141             __android_log_write(ANDROID_LOG_ERROR, TAG, result.error().message().c_str());
142             // Make sure the VM exits so the test will fail solidly
143             exit(1);
144         }
145     }};
146     accept_thread.detach();
147 
148     return {};
149 }
150 
start_test_service()151 Result<void> start_test_service() {
152     class VmCallbackImpl : public BnVmCallback {
153     private:
154         std::shared_ptr<IAppCallback> mAppCallback;
155 
156     public:
157         explicit VmCallbackImpl(const std::shared_ptr<IAppCallback>& appCallback)
158               : mAppCallback(appCallback) {}
159 
160         ScopedAStatus echoMessage(const std::string& message) override {
161             std::thread callback_thread{[=, appCallback = mAppCallback] {
162                 appCallback->onEchoRequestReceived("Received: " + message);
163             }};
164             callback_thread.detach();
165             return ScopedAStatus::ok();
166         }
167     };
168 
169     class TestService : public BnTestService {
170     public:
171         ScopedAStatus addInteger(int32_t a, int32_t b, int32_t* out) override {
172             *out = a + b;
173             return ScopedAStatus::ok();
174         }
175 
176         ScopedAStatus readProperty(const std::string& prop, std::string* out) override {
177             *out = android::base::GetProperty(prop, "");
178             if (out->empty()) {
179                 std::string msg = "cannot find property " + prop;
180                 return ScopedAStatus::fromExceptionCodeWithMessage(EX_SERVICE_SPECIFIC,
181                                                                    msg.c_str());
182             }
183 
184             return ScopedAStatus::ok();
185         }
186 
187         ScopedAStatus insecurelyExposeVmInstanceSecret(std::vector<uint8_t>* out) override {
188             const uint8_t identifier[] = {1, 2, 3, 4};
189             out->resize(32);
190             AVmPayload_getVmInstanceSecret(identifier, sizeof(identifier), out->data(),
191                                            out->size());
192             return ScopedAStatus::ok();
193         }
194 
195         ScopedAStatus insecurelyExposeAttestationCdi(std::vector<uint8_t>* out) override {
196             size_t cdi_size = AVmPayload_getDiceAttestationCdi(nullptr, 0);
197             out->resize(cdi_size);
198             AVmPayload_getDiceAttestationCdi(out->data(), out->size());
199             return ScopedAStatus::ok();
200         }
201 
202         ScopedAStatus getBcc(std::vector<uint8_t>* out) override {
203             size_t bcc_size = AVmPayload_getDiceAttestationChain(nullptr, 0);
204             out->resize(bcc_size);
205             AVmPayload_getDiceAttestationChain(out->data(), out->size());
206             return ScopedAStatus::ok();
207         }
208 
209         ScopedAStatus getApkContentsPath(std::string* out) override {
210             const char* path_c = AVmPayload_getApkContentsPath();
211             if (path_c == nullptr) {
212                 return ScopedAStatus::
213                         fromServiceSpecificErrorWithMessage(0, "Failed to get APK contents path");
214             }
215             *out = path_c;
216             return ScopedAStatus::ok();
217         }
218 
219         ScopedAStatus getEncryptedStoragePath(std::string* out) override {
220             const char* path_c = AVmPayload_getEncryptedStoragePath();
221             if (path_c == nullptr) {
222                 out->clear();
223             } else {
224                 *out = path_c;
225             }
226             return ScopedAStatus::ok();
227         }
228 
229         ScopedAStatus getEffectiveCapabilities(std::vector<std::string>* out) override {
230             if (out == nullptr) {
231                 return ScopedAStatus::ok();
232             }
233             cap_t cap = cap_get_proc();
234             auto guard = make_scope_guard([&cap]() { cap_free(cap); });
235             for (cap_value_t cap_id = 0; cap_id < CAP_LAST_CAP + 1; cap_id++) {
236                 cap_flag_value_t value;
237                 if (cap_get_flag(cap, cap_id, CAP_EFFECTIVE, &value) != 0) {
238                     return ScopedAStatus::
239                             fromServiceSpecificErrorWithMessage(0, "cap_get_flag failed");
240                 }
241                 if (value == CAP_SET) {
242                     // Ideally we would just send back the cap_ids, but I wasn't able to find java
243                     // APIs for linux capabilities, hence we transform to the human readable name
244                     // here.
245                     char* name = cap_to_name(cap_id);
246                     out->push_back(std::string(name) + "(" + std::to_string(cap_id) + ")");
247                 }
248             }
249             return ScopedAStatus::ok();
250         }
251 
252         ScopedAStatus getUid(int* out) override {
253             *out = getuid();
254             return ScopedAStatus::ok();
255         }
256 
257         ScopedAStatus runEchoReverseServer() override {
258             auto result = start_echo_reverse_server();
259             if (result.ok()) {
260                 return ScopedAStatus::ok();
261             } else {
262                 std::string message = result.error().message();
263                 return ScopedAStatus::fromServiceSpecificErrorWithMessage(-1, message.c_str());
264             }
265         }
266 
267         ScopedAStatus writeToFile(const std::string& content, const std::string& path) override {
268             if (!android::base::WriteStringToFile(content, path)) {
269                 std::string msg = "Failed to write " + content + " to file " + path +
270                         ". Errono: " + std::to_string(errno);
271                 return ScopedAStatus::fromExceptionCodeWithMessage(EX_SERVICE_SPECIFIC,
272                                                                    msg.c_str());
273             }
274             return ScopedAStatus::ok();
275         }
276 
277         ScopedAStatus readFromFile(const std::string& path, std::string* out) override {
278             if (!android::base::ReadFileToString(path, out)) {
279                 std::string msg =
280                         "Failed to read " + path + " to string. Errono: " + std::to_string(errno);
281                 return ScopedAStatus::fromExceptionCodeWithMessage(EX_SERVICE_SPECIFIC,
282                                                                    msg.c_str());
283             }
284             return ScopedAStatus::ok();
285         }
286 
287         ScopedAStatus getFilePermissions(const std::string& path, int32_t* out) override {
288             struct stat sb;
289             if (stat(path.c_str(), &sb) != -1) {
290                 *out = sb.st_mode;
291             } else {
292                 std::string msg = "stat " + path + " failed :  " + std::strerror(errno);
293                 return ScopedAStatus::fromExceptionCodeWithMessage(EX_SERVICE_SPECIFIC,
294                                                                    msg.c_str());
295             }
296             return ScopedAStatus::ok();
297         }
298 
299         ScopedAStatus getMountFlags(const std::string& mount_point, int32_t* out) override {
300             Fstab fstab;
301             if (!ReadFstabFromFile("/proc/mounts", &fstab)) {
302                 return ScopedAStatus::fromExceptionCodeWithMessage(EX_SERVICE_SPECIFIC,
303                                                                    "Failed to read /proc/mounts");
304             }
305             FstabEntry* entry = GetEntryForMountPoint(&fstab, mount_point);
306             if (entry == nullptr) {
307                 std::string msg = mount_point + " not found in /proc/mounts";
308                 return ScopedAStatus::fromExceptionCodeWithMessage(EX_SERVICE_SPECIFIC,
309                                                                    msg.c_str());
310             }
311             *out = entry->flags;
312             return ScopedAStatus::ok();
313         }
314 
315         ScopedAStatus getPageSize(int32_t* out) override {
316             *out = getpagesize();
317             return ScopedAStatus::ok();
318         }
319 
320         ScopedAStatus requestCallback(const std::shared_ptr<IAppCallback>& appCallback) {
321             auto vmCallback = ndk::SharedRefBase::make<VmCallbackImpl>(appCallback);
322             std::thread callback_thread{[=] { appCallback->setVmCallback(vmCallback); }};
323             callback_thread.detach();
324             return ScopedAStatus::ok();
325         }
326 
327         ScopedAStatus readLineFromConsole(std::string* out) {
328             FILE* f = fopen("/dev/console", "r");
329             if (f == nullptr) {
330                 return ScopedAStatus::fromExceptionCodeWithMessage(EX_SERVICE_SPECIFIC,
331                                                                    "failed to open /dev/console");
332             }
333             char* line = nullptr;
334             size_t len = 0;
335             ssize_t nread = getline(&line, &len, f);
336 
337             if (nread == -1) {
338                 free(line);
339                 return ScopedAStatus::fromExceptionCodeWithMessage(EX_SERVICE_SPECIFIC,
340                                                                    "failed to read /dev/console");
341             }
342             out->append(line, nread);
343             free(line);
344             return ScopedAStatus::ok();
345         }
346 
347         ScopedAStatus quit() override { exit(0); }
348     };
349     auto testService = ndk::SharedRefBase::make<TestService>();
350 
351     auto callback = []([[maybe_unused]] void* param) { AVmPayload_notifyPayloadReady(); };
352     AVmPayload_runVsockRpcServer(testService->asBinder().get(), testService->PORT, callback,
353                                  nullptr);
354 
355     return {};
356 }
357 
verify_build_manifest()358 Result<void> verify_build_manifest() {
359     const char* path = "/mnt/extra-apk/0/assets/build_manifest.pb";
360 
361     std::string str;
362     if (!android::base::ReadFileToString(path, &str)) {
363         return ErrnoError() << "failed to read build_manifest.pb";
364     }
365 
366     if (!android::security::fsverity::FSVerityDigests().ParseFromString(str)) {
367         return Error() << "invalid build_manifest.pb";
368     }
369 
370     return {};
371 }
372 
verify_vm_share()373 Result<void> verify_vm_share() {
374     const char* path = "/mnt/extra-apk/0/assets/vmshareapp.txt";
375 
376     std::string str;
377     if (!android::base::ReadFileToString(path, &str)) {
378         return ErrnoError() << "failed to read vmshareapp.txt";
379     }
380 
381     return {};
382 }
383 
384 } // Anonymous namespace
385 
AVmPayload_main()386 extern "C" int AVmPayload_main() {
387     __android_log_write(ANDROID_LOG_INFO, TAG, "Hello Microdroid");
388 
389     // Make sure we can call into other shared libraries.
390     testlib_sub();
391 
392     // Report various things that aren't always fatal - these are checked in MicrodroidTests as
393     // appropriate.
394     report_test("extra_apk_build_manifest", verify_build_manifest());
395     report_test("extra_apk_vm_share", verify_vm_share());
396 
397     __system_property_set("debug.microdroid.app.run", "true");
398 
399     if (auto res = start_test_service(); res.ok()) {
400         return 0;
401     } else {
402         __android_log_write(ANDROID_LOG_ERROR, TAG, res.error().message().c_str());
403         return 1;
404     }
405 }
406