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 <string>
38 #include <thread>
39 
40 using android::base::borrowed_fd;
41 using android::base::ErrnoError;
42 using android::base::Error;
43 using android::base::make_scope_guard;
44 using android::base::Result;
45 using android::base::unique_fd;
46 using android::fs_mgr::Fstab;
47 using android::fs_mgr::FstabEntry;
48 using android::fs_mgr::GetEntryForMountPoint;
49 using android::fs_mgr::ReadFstabFromFile;
50 
51 using aidl::com::android::microdroid::testservice::BnTestService;
52 using aidl::com::android::microdroid::testservice::BnVmCallback;
53 using aidl::com::android::microdroid::testservice::IAppCallback;
54 using ndk::ScopedAStatus;
55 
56 extern void testlib_sub();
57 
58 namespace {
59 
60 constexpr char TAG[] = "testbinary";
61 
62 template <typename T>
report_test(std::string name,Result<T> result)63 Result<T> report_test(std::string name, Result<T> result) {
64     auto property = "debug.microdroid.test." + name;
65     std::stringstream outcome;
66     if (result.ok()) {
67         outcome << "PASS";
68     } else {
69         outcome << "FAIL: " << result.error();
70         // 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());
73     }
74     __system_property_set(property.c_str(), outcome.str().c_str());
75     return result;
76 }
77 
run_echo_reverse_server(borrowed_fd listening_fd)78 Result<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 
96     // 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         }
115     }
116 }
117 
start_echo_reverse_server()118 Result<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,
125             .svm_port = static_cast<uint32_t>(BnTestService::ECHO_REVERSE_PORT),
126             .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 
start_test_service()150 Result<void> start_test_service() {
151     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 
168     class TestService : public BnTestService {
169     public:
170         ScopedAStatus addInteger(int32_t a, int32_t b, int32_t* out) override {
171             *out = a + b;
172             return ScopedAStatus::ok();
173         }
174 
175         ScopedAStatus readProperty(const std::string& prop, std::string* out) override {
176             *out = android::base::GetProperty(prop, "");
177             if (out->empty()) {
178                 std::string msg = "cannot find property " + prop;
179                 return ScopedAStatus::fromExceptionCodeWithMessage(EX_SERVICE_SPECIFIC,
180                                                                    msg.c_str());
181             }
182 
183             return ScopedAStatus::ok();
184         }
185 
186         ScopedAStatus insecurelyExposeVmInstanceSecret(std::vector<uint8_t>* out) override {
187             const uint8_t identifier[] = {1, 2, 3, 4};
188             out->resize(32);
189             AVmPayload_getVmInstanceSecret(identifier, sizeof(identifier), out->data(),
190                                            out->size());
191             return ScopedAStatus::ok();
192         }
193 
194         ScopedAStatus insecurelyExposeAttestationCdi(std::vector<uint8_t>* out) override {
195             size_t cdi_size = AVmPayload_getDiceAttestationCdi(nullptr, 0);
196             out->resize(cdi_size);
197             AVmPayload_getDiceAttestationCdi(out->data(), out->size());
198             return ScopedAStatus::ok();
199         }
200 
201         ScopedAStatus getBcc(std::vector<uint8_t>* out) override {
202             size_t bcc_size = AVmPayload_getDiceAttestationChain(nullptr, 0);
203             out->resize(bcc_size);
204             AVmPayload_getDiceAttestationChain(out->data(), out->size());
205             return ScopedAStatus::ok();
206         }
207 
208         ScopedAStatus getApkContentsPath(std::string* out) override {
209             const char* path_c = AVmPayload_getApkContentsPath();
210             if (path_c == nullptr) {
211                 return ScopedAStatus::
212                         fromServiceSpecificErrorWithMessage(0, "Failed to get APK contents path");
213             }
214             *out = path_c;
215             return ScopedAStatus::ok();
216         }
217 
218         ScopedAStatus getEncryptedStoragePath(std::string* out) override {
219             const char* path_c = AVmPayload_getEncryptedStoragePath();
220             if (path_c == nullptr) {
221                 out->clear();
222             } else {
223                 *out = path_c;
224             }
225             return ScopedAStatus::ok();
226         }
227 
228         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 
251         ScopedAStatus getUid(int* out) override {
252             *out = getuid();
253             return ScopedAStatus::ok();
254         }
255 
256         ScopedAStatus runEchoReverseServer() override {
257             auto result = start_echo_reverse_server();
258             if (result.ok()) {
259                 return ScopedAStatus::ok();
260             } else {
261                 std::string message = result.error().message();
262                 return ScopedAStatus::fromServiceSpecificErrorWithMessage(-1, message.c_str());
263             }
264         }
265 
266         ScopedAStatus writeToFile(const std::string& content, const std::string& path) override {
267             if (!android::base::WriteStringToFile(content, path)) {
268                 std::string msg = "Failed to write " + content + " to file " + path +
269                         ". Errono: " + std::to_string(errno);
270                 return ScopedAStatus::fromExceptionCodeWithMessage(EX_SERVICE_SPECIFIC,
271                                                                    msg.c_str());
272             }
273             return ScopedAStatus::ok();
274         }
275 
276         ScopedAStatus readFromFile(const std::string& path, std::string* out) override {
277             if (!android::base::ReadFileToString(path, out)) {
278                 std::string msg =
279                         "Failed to read " + path + " to string. Errono: " + std::to_string(errno);
280                 return ScopedAStatus::fromExceptionCodeWithMessage(EX_SERVICE_SPECIFIC,
281                                                                    msg.c_str());
282             }
283             return ScopedAStatus::ok();
284         }
285 
286         ScopedAStatus getFilePermissions(const std::string& path, int32_t* out) override {
287             struct stat sb;
288             if (stat(path.c_str(), &sb) != -1) {
289                 *out = sb.st_mode;
290             } else {
291                 std::string msg = "stat " + path + " failed :  " + std::strerror(errno);
292                 return ScopedAStatus::fromExceptionCodeWithMessage(EX_SERVICE_SPECIFIC,
293                                                                    msg.c_str());
294             }
295             return ScopedAStatus::ok();
296         }
297 
298         ScopedAStatus getMountFlags(const std::string& mount_point, int32_t* out) override {
299             Fstab fstab;
300             if (!ReadFstabFromFile("/proc/mounts", &fstab)) {
301                 return ScopedAStatus::fromExceptionCodeWithMessage(EX_SERVICE_SPECIFIC,
302                                                                    "Failed to read /proc/mounts");
303             }
304             FstabEntry* entry = GetEntryForMountPoint(&fstab, mount_point);
305             if (entry == nullptr) {
306                 std::string msg = mount_point + " not found in /proc/mounts";
307                 return ScopedAStatus::fromExceptionCodeWithMessage(EX_SERVICE_SPECIFIC,
308                                                                    msg.c_str());
309             }
310             *out = entry->flags;
311             return ScopedAStatus::ok();
312         }
313 
314         ScopedAStatus requestCallback(const std::shared_ptr<IAppCallback>& appCallback) {
315             auto vmCallback = ndk::SharedRefBase::make<VmCallbackImpl>(appCallback);
316             std::thread callback_thread{[=] { appCallback->setVmCallback(vmCallback); }};
317             callback_thread.detach();
318             return ScopedAStatus::ok();
319         }
320 
321         ScopedAStatus readLineFromConsole(std::string* out) {
322             FILE* f = fopen("/dev/console", "r");
323             if (f == nullptr) {
324                 return ScopedAStatus::fromExceptionCodeWithMessage(EX_SERVICE_SPECIFIC,
325                                                                    "failed to open /dev/console");
326             }
327             char* line = nullptr;
328             size_t len = 0;
329             ssize_t nread = getline(&line, &len, f);
330 
331             if (nread == -1) {
332                 free(line);
333                 return ScopedAStatus::fromExceptionCodeWithMessage(EX_SERVICE_SPECIFIC,
334                                                                    "failed to read /dev/console");
335             }
336             out->append(line, nread);
337             free(line);
338             return ScopedAStatus::ok();
339         }
340 
341         ScopedAStatus quit() override { exit(0); }
342     };
343     auto testService = ndk::SharedRefBase::make<TestService>();
344 
345     auto callback = []([[maybe_unused]] void* param) { AVmPayload_notifyPayloadReady(); };
346     AVmPayload_runVsockRpcServer(testService->asBinder().get(), testService->PORT, callback,
347                                  nullptr);
348 
349     return {};
350 }
351 
verify_build_manifest()352 Result<void> verify_build_manifest() {
353     const char* path = "/mnt/extra-apk/0/assets/build_manifest.pb";
354 
355     std::string str;
356     if (!android::base::ReadFileToString(path, &str)) {
357         return ErrnoError() << "failed to read build_manifest.pb";
358     }
359 
360     if (!android::security::fsverity::FSVerityDigests().ParseFromString(str)) {
361         return Error() << "invalid build_manifest.pb";
362     }
363 
364     return {};
365 }
366 
verify_vm_share()367 Result<void> verify_vm_share() {
368     const char* path = "/mnt/extra-apk/0/assets/vmshareapp.txt";
369 
370     std::string str;
371     if (!android::base::ReadFileToString(path, &str)) {
372         return ErrnoError() << "failed to read vmshareapp.txt";
373     }
374 
375     return {};
376 }
377 
378 } // Anonymous namespace
379 
AVmPayload_main()380 extern "C" int AVmPayload_main() {
381     __android_log_write(ANDROID_LOG_INFO, TAG, "Hello Microdroid");
382 
383     // Make sure we can call into other shared libraries.
384     testlib_sub();
385 
386     // Report various things that aren't always fatal - these are checked in MicrodroidTests as
387     // appropriate.
388     report_test("extra_apk_build_manifest", verify_build_manifest());
389     report_test("extra_apk_vm_share", verify_vm_share());
390 
391     __system_property_set("debug.microdroid.app.run", "true");
392 
393     if (auto res = start_test_service(); res.ok()) {
394         return 0;
395     } else {
396         __android_log_write(ANDROID_LOG_ERROR, TAG, res.error().message().c_str());
397         return 1;
398     }
399 }
400