• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 runEchoReverseServer() override {
252             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             }
259         }
260 
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             }
268             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         }
280 
281         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 
293         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 
309         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 
316         ScopedAStatus quit() override { exit(0); }
317     };
318     auto testService = ndk::SharedRefBase::make<TestService>();
319 
320     auto callback = []([[maybe_unused]] void* param) { AVmPayload_notifyPayloadReady(); };
321     AVmPayload_runVsockRpcServer(testService->asBinder().get(), testService->SERVICE_PORT, callback,
322                                  nullptr);
323 
324     return {};
325 }
326 
verify_apk()327 Result<void> verify_apk() {
328     const char* path = "/mnt/extra-apk/0/assets/build_manifest.pb";
329 
330     std::string str;
331     if (!android::base::ReadFileToString(path, &str)) {
332         return ErrnoError() << "failed to read build_manifest.pb";
333     }
334 
335     if (!android::security::fsverity::FSVerityDigests().ParseFromString(str)) {
336         return Error() << "invalid build_manifest.pb";
337     }
338 
339     return {};
340 }
341 
342 } // Anonymous namespace
343 
AVmPayload_main()344 extern "C" int AVmPayload_main() {
345     __android_log_write(ANDROID_LOG_INFO, TAG, "Hello Microdroid");
346 
347     // Make sure we can call into other shared libraries.
348     testlib_sub();
349 
350     // Extra apks may be missing; this is not a fatal error
351     report_test("extra_apk", verify_apk());
352 
353     __system_property_set("debug.microdroid.app.run", "true");
354 
355     if (auto res = start_test_service(); res.ok()) {
356         return 0;
357     } else {
358         __android_log_write(ANDROID_LOG_ERROR, TAG, res.error().message().c_str());
359         return 1;
360     }
361 }
362