1 /*
2  * Copyright (C) 2019 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 "gsi_service.h"
18 
19 #include <sys/statvfs.h>
20 #include <sys/vfs.h>
21 #include <unistd.h>
22 
23 #include <array>
24 #include <chrono>
25 #include <string>
26 #include <vector>
27 
28 #include <android-base/errors.h>
29 #include <android-base/file.h>
30 #include <android-base/logging.h>
31 #include <android-base/properties.h>
32 #include <android-base/stringprintf.h>
33 #include <android-base/strings.h>
34 #include <android/gsi/BnImageService.h>
35 #include <android/gsi/IGsiService.h>
36 #include <android/os/IVold.h>
37 #include <binder/IServiceManager.h>
38 #include <binder/LazyServiceRegistrar.h>
39 #include <ext4_utils/ext4_utils.h>
40 #include <fs_mgr.h>
41 #include <libavb/libavb.h>
42 #include <libdm/dm.h>
43 #include <libfiemap/image_manager.h>
44 #include <openssl/sha.h>
45 #include <private/android_filesystem_config.h>
46 #include <selinux/android.h>
47 #include <storage_literals/storage_literals.h>
48 
49 #include "file_paths.h"
50 #include "libgsi_private.h"
51 
52 namespace android {
53 namespace gsi {
54 
55 using namespace std::literals;
56 using namespace android::fs_mgr;
57 using namespace android::fiemap;
58 using namespace android::storage_literals;
59 using android::base::ReadFileToString;
60 using android::base::ReadFullyAtOffset;
61 using android::base::RemoveFileIfExists;
62 using android::base::SetProperty;
63 using android::base::StringPrintf;
64 using android::base::unique_fd;
65 using android::base::WriteStringToFd;
66 using android::base::WriteStringToFile;
67 using android::binder::LazyServiceRegistrar;
68 using android::dm::DeviceMapper;
69 
70 // Default userdata image size.
71 static constexpr int64_t kDefaultUserdataSize = int64_t(2) * 1024 * 1024 * 1024;
72 
73 static bool GetAvbPublicKeyFromFd(int fd, AvbPublicKey* dst);
74 
75 // Fix the file contexts of dsu metadata files.
76 // By default, newly created files inherit the file contexts of their parent
77 // directory. Since globally readable public metadata files are labeled with a
78 // different context, gsi_public_metadata_file, we need to call this function to
79 // fix their contexts after creating them.
RestoreconMetadataFiles()80 static void RestoreconMetadataFiles() {
81     auto flags = SELINUX_ANDROID_RESTORECON_RECURSE | SELINUX_ANDROID_RESTORECON_SKIP_SEHASH;
82     selinux_android_restorecon(DSU_METADATA_PREFIX, flags);
83 }
84 
GsiService()85 GsiService::GsiService() {
86     progress_ = {};
87 }
88 
Register()89 void GsiService::Register() {
90     auto lazyRegistrar = LazyServiceRegistrar::getInstance();
91     android::sp<GsiService> service = new GsiService();
92     auto ret = lazyRegistrar.registerService(service, kGsiServiceName);
93 
94     if (ret != android::OK) {
95         LOG(FATAL) << "Could not register gsi service: " << ret;
96     }
97 }
98 
99 #define ENFORCE_SYSTEM                      \
100     do {                                    \
101         binder::Status status = CheckUid(); \
102         if (!status.isOk()) return status;  \
103     } while (0)
104 
105 #define ENFORCE_SYSTEM_OR_SHELL                                       \
106     do {                                                              \
107         binder::Status status = CheckUid(AccessLevel::SystemOrShell); \
108         if (!status.isOk()) return status;                            \
109     } while (0)
110 
SaveInstallation(const std::string & installation)111 int GsiService::SaveInstallation(const std::string& installation) {
112     auto dsu_slot = GetDsuSlot(installation);
113     auto install_dir_file = DsuInstallDirFile(dsu_slot);
114     auto metadata_dir = android::base::Dirname(install_dir_file);
115     if (access(metadata_dir.c_str(), F_OK) != 0) {
116         if (mkdir(metadata_dir.c_str(), 0777) != 0) {
117             PLOG(ERROR) << "Failed to mkdir " << metadata_dir;
118             return INSTALL_ERROR_GENERIC;
119         }
120     }
121     auto fd = android::base::unique_fd(
122             open(install_dir_file.c_str(), O_RDWR | O_SYNC | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR));
123     if (!WriteStringToFd(installation, fd)) {
124         PLOG(ERROR) << "write failed: " << DsuInstallDirFile(dsu_slot);
125         return INSTALL_ERROR_GENERIC;
126     }
127     return INSTALL_OK;
128 }
129 
130 static bool IsExternalStoragePath(const std::string& path);
131 
openInstall(const std::string & install_dir,int * _aidl_return)132 binder::Status GsiService::openInstall(const std::string& install_dir, int* _aidl_return) {
133     ENFORCE_SYSTEM;
134     std::lock_guard<std::mutex> guard(lock_);
135     if (IsGsiRunning()) {
136         *_aidl_return = IGsiService::INSTALL_ERROR_GENERIC;
137         return binder::Status::ok();
138     }
139     install_dir_ = install_dir;
140     if (int status = ValidateInstallParams(install_dir_)) {
141         *_aidl_return = status;
142         return binder::Status::ok();
143     }
144     std::string message;
145     auto dsu_slot = GetDsuSlot(install_dir_);
146     if (!RemoveFileIfExists(GetCompleteIndication(dsu_slot), &message)) {
147         LOG(ERROR) << message;
148     }
149     // Remember the installation directory before allocate any resource
150     *_aidl_return = SaveInstallation(install_dir_);
151     return binder::Status::ok();
152 }
153 
closeInstall(int * _aidl_return)154 binder::Status GsiService::closeInstall(int* _aidl_return) {
155     ENFORCE_SYSTEM;
156     std::lock_guard<std::mutex> guard(lock_);
157     auto dsu_slot = GetDsuSlot(install_dir_);
158     std::string file = GetCompleteIndication(dsu_slot);
159     if (!WriteStringToFile("OK", file)) {
160         PLOG(ERROR) << "write failed: " << file;
161         *_aidl_return = INSTALL_ERROR_GENERIC;
162     }
163     *_aidl_return = INSTALL_OK;
164     return binder::Status::ok();
165 }
166 
createPartition(const::std::string & name,int64_t size,bool readOnly,int32_t * _aidl_return)167 binder::Status GsiService::createPartition(const ::std::string& name, int64_t size, bool readOnly,
168                                            int32_t* _aidl_return) {
169     ENFORCE_SYSTEM;
170     std::lock_guard<std::mutex> guard(lock_);
171 
172     if (install_dir_.empty()) {
173         PLOG(ERROR) << "open is required for createPartition";
174         *_aidl_return = INSTALL_ERROR_GENERIC;
175         return binder::Status::ok();
176     }
177 
178     // Do some precursor validation on the arguments before diving into the
179     // install process.
180     if (size % LP_SECTOR_SIZE) {
181         LOG(ERROR) << " size " << size << " is not a multiple of " << LP_SECTOR_SIZE;
182         *_aidl_return = INSTALL_ERROR_GENERIC;
183         return binder::Status::ok();
184     }
185 
186     if (size == 0 && name == "userdata") {
187         size = kDefaultUserdataSize;
188     }
189 
190     if (name == "userdata") {
191         auto dsu_slot = GetDsuSlot(install_dir_);
192         auto key_dir = DefaultDsuMetadataKeyDir(dsu_slot);
193         auto key_dir_file = DsuMetadataKeyDirFile(dsu_slot);
194         if (!android::base::WriteStringToFile(key_dir, key_dir_file)) {
195             PLOG(ERROR) << "write failed: " << key_dir_file;
196             *_aidl_return = INSTALL_ERROR_GENERIC;
197             return binder::Status::ok();
198         }
199         RestoreconMetadataFiles();
200     }
201 
202     installer_ = std::make_unique<PartitionInstaller>(this, install_dir_, name,
203                                                       GetDsuSlot(install_dir_), size, readOnly);
204     progress_ = {};
205     *_aidl_return = installer_->StartInstall();
206     return binder::Status::ok();
207 }
208 
closePartition(int32_t * _aidl_return)209 binder::Status GsiService::closePartition(int32_t* _aidl_return) {
210     ENFORCE_SYSTEM;
211     std::lock_guard<std::mutex> guard(lock_);
212 
213     if (installer_ == nullptr) {
214         LOG(ERROR) << "createPartition() has to be called before closePartition()";
215         *_aidl_return = IGsiService::INSTALL_ERROR_GENERIC;
216         return binder::Status::ok();
217     }
218     // It is important to not reset |installer_| here because other methods such
219     // as enableGsi() relies on the state of |installer_|.
220     *_aidl_return = installer_->FinishInstall();
221     return binder::Status::ok();
222 }
223 
commitGsiChunkFromStream(const android::os::ParcelFileDescriptor & stream,int64_t bytes,bool * _aidl_return)224 binder::Status GsiService::commitGsiChunkFromStream(const android::os::ParcelFileDescriptor& stream,
225                                                     int64_t bytes, bool* _aidl_return) {
226     ENFORCE_SYSTEM;
227     std::lock_guard<std::mutex> guard(lock_);
228 
229     if (!installer_) {
230         *_aidl_return = false;
231         return binder::Status::ok();
232     }
233 
234     *_aidl_return = installer_->CommitGsiChunk(stream.get(), bytes);
235     return binder::Status::ok();
236 }
237 
StartAsyncOperation(const std::string & step,int64_t total_bytes)238 void GsiService::StartAsyncOperation(const std::string& step, int64_t total_bytes) {
239     std::lock_guard<std::mutex> guard(progress_lock_);
240 
241     progress_.step = step;
242     progress_.status = STATUS_WORKING;
243     progress_.bytes_processed = 0;
244     progress_.total_bytes = total_bytes;
245 }
246 
UpdateProgress(int status,int64_t bytes_processed)247 void GsiService::UpdateProgress(int status, int64_t bytes_processed) {
248     std::lock_guard<std::mutex> guard(progress_lock_);
249 
250     progress_.status = status;
251     if (status == STATUS_COMPLETE) {
252         progress_.bytes_processed = progress_.total_bytes;
253     } else {
254         progress_.bytes_processed = bytes_processed;
255     }
256 }
257 
getInstallProgress(::android::gsi::GsiProgress * _aidl_return)258 binder::Status GsiService::getInstallProgress(::android::gsi::GsiProgress* _aidl_return) {
259     ENFORCE_SYSTEM;
260     std::lock_guard<std::mutex> guard(progress_lock_);
261 
262     if (installer_ == nullptr) {
263         progress_ = {};
264     }
265     *_aidl_return = progress_;
266     return binder::Status::ok();
267 }
268 
commitGsiChunkFromAshmem(int64_t bytes,bool * _aidl_return)269 binder::Status GsiService::commitGsiChunkFromAshmem(int64_t bytes, bool* _aidl_return) {
270     ENFORCE_SYSTEM;
271     std::lock_guard<std::mutex> guard(lock_);
272 
273     if (!installer_) {
274         *_aidl_return = false;
275         return binder::Status::ok();
276     }
277     *_aidl_return = installer_->CommitGsiChunk(bytes);
278     return binder::Status::ok();
279 }
280 
setGsiAshmem(const::android::os::ParcelFileDescriptor & ashmem,int64_t size,bool * _aidl_return)281 binder::Status GsiService::setGsiAshmem(const ::android::os::ParcelFileDescriptor& ashmem,
282                                         int64_t size, bool* _aidl_return) {
283     ENFORCE_SYSTEM;
284     if (!installer_) {
285         *_aidl_return = false;
286         return binder::Status::ok();
287     }
288     *_aidl_return = installer_->MapAshmem(ashmem.get(), size);
289     return binder::Status::ok();
290 }
291 
enableGsiAsync(bool one_shot,const std::string & dsuSlot,const sp<IGsiServiceCallback> & resultCallback)292 binder::Status GsiService::enableGsiAsync(bool one_shot, const std::string& dsuSlot,
293                                           const sp<IGsiServiceCallback>& resultCallback) {
294     int result;
295     auto status = enableGsi(one_shot, dsuSlot, &result);
296     if (!status.isOk()) {
297         LOG(ERROR) << "Could not enableGsi: " << status.exceptionMessage().string();
298         result = IGsiService::INSTALL_ERROR_GENERIC;
299     }
300     resultCallback->onResult(result);
301     return binder::Status::ok();
302 }
303 
enableGsi(bool one_shot,const std::string & dsuSlot,int * _aidl_return)304 binder::Status GsiService::enableGsi(bool one_shot, const std::string& dsuSlot, int* _aidl_return) {
305     std::lock_guard<std::mutex> guard(lock_);
306 
307     if (!WriteStringToFile(dsuSlot, kDsuActiveFile)) {
308         PLOG(ERROR) << "write failed: " << GetDsuSlot(install_dir_);
309         *_aidl_return = INSTALL_ERROR_GENERIC;
310         return binder::Status::ok();
311     }
312     RestoreconMetadataFiles();
313     if (installer_) {
314         ENFORCE_SYSTEM;
315         installer_ = {};
316         // Note: create the install status file last, since this is the actual boot
317         // indicator.
318         if (!SetBootMode(one_shot) || !CreateInstallStatusFile()) {
319             *_aidl_return = IGsiService::INSTALL_ERROR_GENERIC;
320         } else {
321             *_aidl_return = INSTALL_OK;
322         }
323     } else {
324         ENFORCE_SYSTEM_OR_SHELL;
325         *_aidl_return = ReenableGsi(one_shot);
326     }
327 
328     installer_ = nullptr;
329     return binder::Status::ok();
330 }
331 
isGsiEnabled(bool * _aidl_return)332 binder::Status GsiService::isGsiEnabled(bool* _aidl_return) {
333     ENFORCE_SYSTEM_OR_SHELL;
334     std::lock_guard<std::mutex> guard(lock_);
335     std::string boot_key;
336     if (!GetInstallStatus(&boot_key)) {
337         *_aidl_return = false;
338     } else {
339         *_aidl_return = (boot_key != kInstallStatusDisabled);
340     }
341     return binder::Status::ok();
342 }
343 
removeGsiAsync(const sp<IGsiServiceCallback> & resultCallback)344 binder::Status GsiService::removeGsiAsync(const sp<IGsiServiceCallback>& resultCallback) {
345     bool result;
346     auto status = removeGsi(&result);
347     if (!status.isOk()) {
348         LOG(ERROR) << "Could not removeGsi: " << status.exceptionMessage().string();
349         result = IGsiService::INSTALL_ERROR_GENERIC;
350     }
351     resultCallback->onResult(result);
352     return binder::Status::ok();
353 }
354 
removeGsi(bool * _aidl_return)355 binder::Status GsiService::removeGsi(bool* _aidl_return) {
356     ENFORCE_SYSTEM_OR_SHELL;
357     std::lock_guard<std::mutex> guard(lock_);
358 
359     std::string install_dir = GetActiveInstalledImageDir();
360     if (IsGsiRunning()) {
361         // Can't remove gsi files while running.
362         *_aidl_return = UninstallGsi();
363     } else {
364         installer_ = {};
365         *_aidl_return = RemoveGsiFiles(install_dir);
366     }
367     return binder::Status::ok();
368 }
369 
disableGsi(bool * _aidl_return)370 binder::Status GsiService::disableGsi(bool* _aidl_return) {
371     ENFORCE_SYSTEM_OR_SHELL;
372     std::lock_guard<std::mutex> guard(lock_);
373 
374     *_aidl_return = DisableGsiInstall();
375     return binder::Status::ok();
376 }
377 
isGsiRunning(bool * _aidl_return)378 binder::Status GsiService::isGsiRunning(bool* _aidl_return) {
379     ENFORCE_SYSTEM_OR_SHELL;
380     std::lock_guard<std::mutex> guard(lock_);
381 
382     *_aidl_return = IsGsiRunning();
383     return binder::Status::ok();
384 }
385 
isGsiInstalled(bool * _aidl_return)386 binder::Status GsiService::isGsiInstalled(bool* _aidl_return) {
387     ENFORCE_SYSTEM_OR_SHELL;
388     std::lock_guard<std::mutex> guard(lock_);
389 
390     *_aidl_return = IsGsiInstalled();
391     return binder::Status::ok();
392 }
393 
isGsiInstallInProgress(bool * _aidl_return)394 binder::Status GsiService::isGsiInstallInProgress(bool* _aidl_return) {
395     ENFORCE_SYSTEM_OR_SHELL;
396     std::lock_guard<std::mutex> guard(lock_);
397 
398     *_aidl_return = !!installer_;
399     return binder::Status::ok();
400 }
401 
cancelGsiInstall(bool * _aidl_return)402 binder::Status GsiService::cancelGsiInstall(bool* _aidl_return) {
403     ENFORCE_SYSTEM;
404     should_abort_ = true;
405     std::lock_guard<std::mutex> guard(lock_);
406 
407     should_abort_ = false;
408     installer_ = nullptr;
409 
410     *_aidl_return = true;
411     return binder::Status::ok();
412 }
413 
getInstalledGsiImageDir(std::string * _aidl_return)414 binder::Status GsiService::getInstalledGsiImageDir(std::string* _aidl_return) {
415     ENFORCE_SYSTEM;
416     std::lock_guard<std::mutex> guard(lock_);
417 
418     *_aidl_return = GetActiveInstalledImageDir();
419     return binder::Status::ok();
420 }
421 
getActiveDsuSlot(std::string * _aidl_return)422 binder::Status GsiService::getActiveDsuSlot(std::string* _aidl_return) {
423     ENFORCE_SYSTEM_OR_SHELL;
424     std::lock_guard<std::mutex> guard(lock_);
425 
426     *_aidl_return = GetActiveDsuSlot();
427     return binder::Status::ok();
428 }
429 
getInstalledDsuSlots(std::vector<std::string> * _aidl_return)430 binder::Status GsiService::getInstalledDsuSlots(std::vector<std::string>* _aidl_return) {
431     ENFORCE_SYSTEM;
432     std::lock_guard<std::mutex> guard(lock_);
433     *_aidl_return = GetInstalledDsuSlots();
434     return binder::Status::ok();
435 }
436 
zeroPartition(const std::string & name,int * _aidl_return)437 binder::Status GsiService::zeroPartition(const std::string& name, int* _aidl_return) {
438     ENFORCE_SYSTEM_OR_SHELL;
439     std::lock_guard<std::mutex> guard(lock_);
440 
441     if (IsGsiRunning() || !IsGsiInstalled()) {
442         *_aidl_return = IGsiService::INSTALL_ERROR_GENERIC;
443         return binder::Status::ok();
444     }
445 
446     std::string install_dir = GetActiveInstalledImageDir();
447     *_aidl_return = PartitionInstaller::WipeWritable(GetDsuSlot(install_dir), install_dir, name);
448 
449     return binder::Status::ok();
450 }
451 
BinderError(const std::string & message,FiemapStatus::ErrorCode status=FiemapStatus::ErrorCode::ERROR)452 static binder::Status BinderError(const std::string& message,
453                                   FiemapStatus::ErrorCode status = FiemapStatus::ErrorCode::ERROR) {
454     return binder::Status::fromServiceSpecificError(static_cast<int32_t>(status), message.c_str());
455 }
456 
dumpDeviceMapperDevices(std::string * _aidl_return)457 binder::Status GsiService::dumpDeviceMapperDevices(std::string* _aidl_return) {
458     ENFORCE_SYSTEM_OR_SHELL;
459 
460     auto& dm = DeviceMapper::Instance();
461 
462     std::vector<DeviceMapper::DmBlockDevice> devices;
463     if (!dm.GetAvailableDevices(&devices)) {
464         return BinderError("Could not list devices");
465     }
466 
467     std::stringstream text;
468     for (const auto& device : devices) {
469         text << "Device " << device.name() << " (" << device.Major() << ":" << device.Minor()
470              << ")\n";
471 
472         std::vector<DeviceMapper::TargetInfo> table;
473         if (!dm.GetTableInfo(device.name(), &table)) {
474             continue;
475         }
476 
477         for (const auto& target : table) {
478             const auto& spec = target.spec;
479             auto target_type = DeviceMapper::GetTargetType(spec);
480             text << "    " << target_type << " " << spec.sector_start << " " << spec.length << " "
481                  << target.data << "\n";
482         }
483     }
484 
485     *_aidl_return = text.str();
486     return binder::Status::ok();
487 }
488 
getAvbPublicKey(AvbPublicKey * dst,int32_t * _aidl_return)489 binder::Status GsiService::getAvbPublicKey(AvbPublicKey* dst, int32_t* _aidl_return) {
490     ENFORCE_SYSTEM;
491     std::lock_guard<std::mutex> guard(lock_);
492 
493     if (!installer_) {
494         *_aidl_return = INSTALL_ERROR_GENERIC;
495         return binder::Status::ok();
496     }
497     int fd = installer_->GetPartitionFd();
498     if (!GetAvbPublicKeyFromFd(fd, dst)) {
499         LOG(ERROR) << "Failed to extract AVB public key";
500         *_aidl_return = INSTALL_ERROR_GENERIC;
501         return binder::Status::ok();
502     }
503     *_aidl_return = INSTALL_OK;
504     return binder::Status::ok();
505 }
506 
suggestScratchSize(int64_t * _aidl_return)507 binder::Status GsiService::suggestScratchSize(int64_t* _aidl_return) {
508     ENFORCE_SYSTEM;
509 
510     static constexpr uint64_t kMinScratchSize = 512_MiB;
511     static constexpr uint64_t kMaxScratchSize = 2_GiB;
512 
513     uint64_t size = 0;
514     struct statvfs info;
515     if (statvfs(install_dir_.c_str(), &info)) {
516         PLOG(ERROR) << "Could not statvfs(" << install_dir_ << ")";
517     } else {
518         // Keep the storage device at least 40% free, plus 1% for jitter.
519         constexpr int jitter = 1;
520         const uint64_t reserved_blocks =
521                 static_cast<uint64_t>(info.f_blocks) * (kMinimumFreeSpaceThreshold + jitter) / 100;
522         if (info.f_bavail > reserved_blocks) {
523             size = (info.f_bavail - reserved_blocks) * info.f_frsize;
524         }
525     }
526 
527     // We can safely downcast the result here, since we clamped the result within int64_t range.
528     *_aidl_return = std::clamp(size, kMinScratchSize, kMaxScratchSize);
529     return binder::Status::ok();
530 }
531 
CreateInstallStatusFile()532 bool GsiService::CreateInstallStatusFile() {
533     if (!android::base::WriteStringToFile("0", kDsuInstallStatusFile)) {
534         PLOG(ERROR) << "write " << kDsuInstallStatusFile;
535         return false;
536     }
537     SetProperty(kGsiInstalledProp, "1");
538     return true;
539 }
540 
SetBootMode(bool one_shot)541 bool GsiService::SetBootMode(bool one_shot) {
542     if (one_shot) {
543         if (!android::base::WriteStringToFile("1", kDsuOneShotBootFile)) {
544             PLOG(ERROR) << "write " << kDsuOneShotBootFile;
545             return false;
546         }
547     } else if (!access(kDsuOneShotBootFile, F_OK)) {
548         std::string error;
549         if (!android::base::RemoveFileIfExists(kDsuOneShotBootFile, &error)) {
550             LOG(ERROR) << error;
551             return false;
552         }
553     }
554     return true;
555 }
556 
UidSecurityError()557 static binder::Status UidSecurityError() {
558     uid_t uid = IPCThreadState::self()->getCallingUid();
559     auto message = StringPrintf("UID %d is not allowed", uid);
560     return binder::Status::fromExceptionCode(binder::Status::EX_SECURITY, String8(message.c_str()));
561 }
562 
563 class ImageService : public BinderService<ImageService>, public BnImageService {
564   public:
565     ImageService(GsiService* service, std::unique_ptr<ImageManager>&& impl, uid_t uid);
566     binder::Status getAllBackingImages(std::vector<std::string>* _aidl_return);
567     binder::Status createBackingImage(const std::string& name, int64_t size, int flags,
568                                       const sp<IProgressCallback>& on_progress) override;
569     binder::Status deleteBackingImage(const std::string& name) override;
570     binder::Status mapImageDevice(const std::string& name, int32_t timeout_ms,
571                                   MappedImage* mapping) override;
572     binder::Status unmapImageDevice(const std::string& name) override;
573     binder::Status backingImageExists(const std::string& name, bool* _aidl_return) override;
574     binder::Status isImageMapped(const std::string& name, bool* _aidl_return) override;
575     binder::Status getAvbPublicKey(const std::string& name, AvbPublicKey* dst,
576                                    int32_t* _aidl_return) override;
577     binder::Status zeroFillNewImage(const std::string& name, int64_t bytes) override;
578     binder::Status removeAllImages() override;
579     binder::Status removeDisabledImages() override;
580     binder::Status getMappedImageDevice(const std::string& name, std::string* device) override;
581 
582   private:
583     bool CheckUid();
584 
585     android::sp<GsiService> service_;
586     std::unique_ptr<ImageManager> impl_;
587     uid_t uid_;
588 };
589 
ImageService(GsiService * service,std::unique_ptr<ImageManager> && impl,uid_t uid)590 ImageService::ImageService(GsiService* service, std::unique_ptr<ImageManager>&& impl, uid_t uid)
591     : service_(service), impl_(std::move(impl)), uid_(uid) {}
592 
getAllBackingImages(std::vector<std::string> * _aidl_return)593 binder::Status ImageService::getAllBackingImages(std::vector<std::string>* _aidl_return) {
594     *_aidl_return = impl_->GetAllBackingImages();
595     return binder::Status::ok();
596 }
597 
createBackingImage(const std::string & name,int64_t size,int flags,const sp<IProgressCallback> & on_progress)598 binder::Status ImageService::createBackingImage(const std::string& name, int64_t size, int flags,
599                                                 const sp<IProgressCallback>& on_progress) {
600     if (!CheckUid()) return UidSecurityError();
601 
602     std::lock_guard<std::mutex> guard(service_->lock());
603 
604     std::function<bool(uint64_t, uint64_t)> callback;
605     if (on_progress) {
606         callback = [on_progress](uint64_t current, uint64_t total) -> bool {
607             auto status = on_progress->onProgress(static_cast<int64_t>(current),
608                                                   static_cast<int64_t>(total));
609             if (!status.isOk()) {
610                 LOG(ERROR) << "progress callback returned: " << status.toString8().string();
611                 return false;
612             }
613             return true;
614         };
615     }
616 
617     auto res = impl_->CreateBackingImage(name, size, flags, std::move(callback));
618     if (!res.is_ok()) {
619         return BinderError("Failed to create: " + res.string(), res.error_code());
620     }
621     return binder::Status::ok();
622 }
623 
deleteBackingImage(const std::string & name)624 binder::Status ImageService::deleteBackingImage(const std::string& name) {
625     if (!CheckUid()) return UidSecurityError();
626 
627     std::lock_guard<std::mutex> guard(service_->lock());
628 
629     if (!impl_->DeleteBackingImage(name)) {
630         return BinderError("Failed to delete");
631     }
632     return binder::Status::ok();
633 }
634 
mapImageDevice(const std::string & name,int32_t timeout_ms,MappedImage * mapping)635 binder::Status ImageService::mapImageDevice(const std::string& name, int32_t timeout_ms,
636                                             MappedImage* mapping) {
637     if (!CheckUid()) return UidSecurityError();
638 
639     std::lock_guard<std::mutex> guard(service_->lock());
640 
641     if (!impl_->MapImageDevice(name, std::chrono::milliseconds(timeout_ms), &mapping->path)) {
642         return BinderError("Failed to map");
643     }
644     return binder::Status::ok();
645 }
646 
unmapImageDevice(const std::string & name)647 binder::Status ImageService::unmapImageDevice(const std::string& name) {
648     if (!CheckUid()) return UidSecurityError();
649 
650     std::lock_guard<std::mutex> guard(service_->lock());
651 
652     if (!impl_->UnmapImageDevice(name)) {
653         return BinderError("Failed to unmap");
654     }
655     return binder::Status::ok();
656 }
657 
backingImageExists(const std::string & name,bool * _aidl_return)658 binder::Status ImageService::backingImageExists(const std::string& name, bool* _aidl_return) {
659     if (!CheckUid()) return UidSecurityError();
660 
661     std::lock_guard<std::mutex> guard(service_->lock());
662 
663     *_aidl_return = impl_->BackingImageExists(name);
664     return binder::Status::ok();
665 }
666 
isImageMapped(const std::string & name,bool * _aidl_return)667 binder::Status ImageService::isImageMapped(const std::string& name, bool* _aidl_return) {
668     if (!CheckUid()) return UidSecurityError();
669 
670     std::lock_guard<std::mutex> guard(service_->lock());
671 
672     *_aidl_return = impl_->IsImageMapped(name);
673     return binder::Status::ok();
674 }
675 
getAvbPublicKey(const std::string & name,AvbPublicKey * dst,int32_t * _aidl_return)676 binder::Status ImageService::getAvbPublicKey(const std::string& name, AvbPublicKey* dst,
677                                              int32_t* _aidl_return) {
678     if (!CheckUid()) return UidSecurityError();
679 
680     std::lock_guard<std::mutex> guard(service_->lock());
681 
682     std::string device_path;
683     std::unique_ptr<MappedDevice> mapped_device;
684     if (!impl_->IsImageMapped(name)) {
685         mapped_device = MappedDevice::Open(impl_.get(), 10s, name);
686         if (!mapped_device) {
687             PLOG(ERROR) << "Fail to map image: " << name;
688             *_aidl_return = IMAGE_ERROR;
689             return binder::Status::ok();
690         }
691         device_path = mapped_device->path();
692     } else {
693         if (!impl_->GetMappedImageDevice(name, &device_path)) {
694             PLOG(ERROR) << "GetMappedImageDevice() failed";
695             *_aidl_return = IMAGE_ERROR;
696             return binder::Status::ok();
697         }
698     }
699     android::base::unique_fd fd(open(device_path.c_str(), O_RDONLY | O_CLOEXEC));
700     if (!fd.ok()) {
701         PLOG(ERROR) << "Fail to open mapped device: " << device_path;
702         *_aidl_return = IMAGE_ERROR;
703         return binder::Status::ok();
704     }
705     bool ok = GetAvbPublicKeyFromFd(fd.get(), dst);
706     fd = {};
707     if (!ok) {
708         LOG(ERROR) << "Failed to extract AVB public key";
709         *_aidl_return = IMAGE_ERROR;
710         return binder::Status::ok();
711     }
712     *_aidl_return = IMAGE_OK;
713     return binder::Status::ok();
714 }
715 
zeroFillNewImage(const std::string & name,int64_t bytes)716 binder::Status ImageService::zeroFillNewImage(const std::string& name, int64_t bytes) {
717     if (!CheckUid()) return UidSecurityError();
718 
719     std::lock_guard<std::mutex> guard(service_->lock());
720 
721     if (bytes < 0) {
722         return BinderError("Cannot use negative values");
723     }
724     auto res = impl_->ZeroFillNewImage(name, bytes);
725     if (!res.is_ok()) {
726         return BinderError("Failed to fill image with zeros: " + res.string(), res.error_code());
727     }
728     return binder::Status::ok();
729 }
730 
removeAllImages()731 binder::Status ImageService::removeAllImages() {
732     if (!CheckUid()) return UidSecurityError();
733 
734     std::lock_guard<std::mutex> guard(service_->lock());
735     if (!impl_->RemoveAllImages()) {
736         return BinderError("Failed to remove all images");
737     }
738     return binder::Status::ok();
739 }
740 
removeDisabledImages()741 binder::Status ImageService::removeDisabledImages() {
742     if (!CheckUid()) return UidSecurityError();
743 
744     std::lock_guard<std::mutex> guard(service_->lock());
745     if (!impl_->RemoveDisabledImages()) {
746         return BinderError("Failed to remove disabled images");
747     }
748     return binder::Status::ok();
749 }
750 
getMappedImageDevice(const std::string & name,std::string * device)751 binder::Status ImageService::getMappedImageDevice(const std::string& name, std::string* device) {
752     if (!CheckUid()) return UidSecurityError();
753 
754     std::lock_guard<std::mutex> guard(service_->lock());
755     if (!impl_->GetMappedImageDevice(name, device)) {
756         *device = "";
757     }
758     return binder::Status::ok();
759 }
760 
CheckUid()761 bool ImageService::CheckUid() {
762     return uid_ == IPCThreadState::self()->getCallingUid();
763 }
764 
openImageService(const std::string & prefix,android::sp<IImageService> * _aidl_return)765 binder::Status GsiService::openImageService(const std::string& prefix,
766                                             android::sp<IImageService>* _aidl_return) {
767     using android::base::StartsWith;
768 
769     static constexpr char kImageMetadataPrefix[] = "/metadata/gsi/";
770     static constexpr char kImageDataPrefix[] = "/data/gsi/";
771 
772     auto in_metadata_dir = kImageMetadataPrefix + prefix;
773     auto in_data_dir = kImageDataPrefix + prefix;
774     auto install_dir_file = DsuInstallDirFile(GetDsuSlot(prefix));
775 
776     std::string in_data_dir_tmp;
777     if (android::base::ReadFileToString(install_dir_file, &in_data_dir_tmp)) {
778         in_data_dir = in_data_dir_tmp;
779         LOG(INFO) << "load " << install_dir_file << ":" << in_data_dir;
780     }
781     std::string metadata_dir, data_dir;
782     if (!android::base::Realpath(in_metadata_dir, &metadata_dir)) {
783         PLOG(ERROR) << "realpath failed for metadata: " << in_metadata_dir;
784         return BinderError("Invalid path");
785     }
786     if (!android::base::Realpath(in_data_dir, &data_dir)) {
787         PLOG(ERROR) << "realpath failed for data: " << in_data_dir;
788         return BinderError("Invalid path");
789     }
790     if (!StartsWith(metadata_dir, kImageMetadataPrefix)) {
791         return BinderError("Invalid metadata path");
792     }
793     if (!StartsWith(data_dir, kImageDataPrefix) && !StartsWith(data_dir, kDsuSDPrefix)) {
794         return BinderError("Invalid data path");
795     }
796 
797     uid_t uid = IPCThreadState::self()->getCallingUid();
798     if (uid != AID_ROOT) {
799         return UidSecurityError();
800     }
801 
802     auto impl = ImageManager::Open(metadata_dir, data_dir);
803     if (!impl) {
804         return BinderError("Unknown error");
805     }
806 
807     *_aidl_return = new ImageService(this, std::move(impl), uid);
808     return binder::Status::ok();
809 }
810 
CheckUid(AccessLevel level)811 binder::Status GsiService::CheckUid(AccessLevel level) {
812     std::vector<uid_t> allowed_uids{AID_ROOT, AID_SYSTEM};
813     if (level == AccessLevel::SystemOrShell) {
814         allowed_uids.push_back(AID_SHELL);
815     }
816 
817     uid_t uid = IPCThreadState::self()->getCallingUid();
818     for (const auto& allowed_uid : allowed_uids) {
819         if (allowed_uid == uid) {
820             return binder::Status::ok();
821         }
822     }
823     return UidSecurityError();
824 }
825 
IsExternalStoragePath(const std::string & path)826 static bool IsExternalStoragePath(const std::string& path) {
827     if (!android::base::StartsWith(path, kDsuSDPrefix)) {
828         return false;
829     }
830     unique_fd fd(open(path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
831     if (fd < 0) {
832         PLOG(ERROR) << "open failed: " << path;
833         return false;
834     }
835     struct statfs info;
836     if (fstatfs(fd, &info)) {
837         PLOG(ERROR) << "statfs failed: " << path;
838         return false;
839     }
840     LOG(ERROR) << "fs type: " << info.f_type;
841     return info.f_type == MSDOS_SUPER_MAGIC;
842 }
843 
ValidateInstallParams(std::string & install_dir)844 int GsiService::ValidateInstallParams(std::string& install_dir) {
845     // If no install path was specified, use the default path. We also allow
846     // specifying the top-level folder, and then we choose the correct location
847     // underneath.
848     if (install_dir.empty() || install_dir == "/data/gsi") {
849         install_dir = kDefaultDsuImageFolder;
850     }
851 
852     if (access(install_dir.c_str(), F_OK) != 0 && (errno == ENOENT)) {
853         if (android::base::StartsWith(install_dir, kDsuSDPrefix)) {
854             if (mkdir(install_dir.c_str(), 0755) != 0) {
855                 PLOG(ERROR) << "Failed to create " << install_dir;
856                 return INSTALL_ERROR_GENERIC;
857             }
858         }
859     }
860     // Normalize the path and add a trailing slash.
861     std::string origInstallDir = install_dir;
862     if (!android::base::Realpath(origInstallDir, &install_dir)) {
863         PLOG(ERROR) << "realpath failed: " << origInstallDir;
864         return INSTALL_ERROR_GENERIC;
865     }
866     // Ensure the path ends in / for consistency.
867     if (!android::base::EndsWith(install_dir, "/")) {
868         install_dir += "/";
869     }
870 
871     // Currently, we can only install to /data/gsi/ or external storage.
872     if (IsExternalStoragePath(install_dir)) {
873         Fstab fstab;
874         if (!ReadDefaultFstab(&fstab)) {
875             LOG(ERROR) << "cannot read default fstab";
876             return INSTALL_ERROR_GENERIC;
877         }
878         FstabEntry* system = GetEntryForMountPoint(&fstab, "/system");
879         if (!system) {
880             LOG(ERROR) << "cannot find /system fstab entry";
881             return INSTALL_ERROR_GENERIC;
882         }
883         if (fs_mgr_verity_is_check_at_most_once(*system)) {
884             LOG(ERROR) << "cannot install GSIs to external media if verity uses check_at_most_once";
885             return INSTALL_ERROR_GENERIC;
886         }
887     } else if (install_dir != kDefaultDsuImageFolder) {
888         LOG(ERROR) << "cannot install DSU to " << install_dir;
889         return INSTALL_ERROR_GENERIC;
890     }
891     return INSTALL_OK;
892 }
893 
GetActiveDsuSlot()894 std::string GsiService::GetActiveDsuSlot() {
895     if (!install_dir_.empty()) {
896         return GetDsuSlot(install_dir_);
897     } else {
898         std::string active_dsu;
899         return GetActiveDsu(&active_dsu) ? active_dsu : "";
900     }
901 }
902 
GetActiveInstalledImageDir()903 std::string GsiService::GetActiveInstalledImageDir() {
904     // Just in case an install was left hanging.
905     if (installer_) {
906         return installer_->install_dir();
907     } else {
908         return GetInstalledImageDir();
909     }
910 }
911 
GetInstalledImageDir()912 std::string GsiService::GetInstalledImageDir() {
913     // If there's no install left, just return /data/gsi since that's where
914     // installs go by default.
915     std::string active_dsu;
916     std::string dir;
917     if (GetActiveDsu(&active_dsu) &&
918         android::base::ReadFileToString(DsuInstallDirFile(active_dsu), &dir)) {
919         return dir;
920     }
921     return kDefaultDsuImageFolder;
922 }
923 
ReenableGsi(bool one_shot)924 int GsiService::ReenableGsi(bool one_shot) {
925     if (!android::gsi::IsGsiInstalled()) {
926         LOG(ERROR) << "no gsi installed - cannot re-enable";
927         return INSTALL_ERROR_GENERIC;
928     }
929     std::string boot_key;
930     if (!GetInstallStatus(&boot_key)) {
931         PLOG(ERROR) << "read " << kDsuInstallStatusFile;
932         return INSTALL_ERROR_GENERIC;
933     }
934     if (boot_key != kInstallStatusDisabled) {
935         LOG(ERROR) << "GSI is not currently disabled";
936         return INSTALL_ERROR_GENERIC;
937     }
938     if (IsGsiRunning()) {
939         if (!SetBootMode(one_shot) || !CreateInstallStatusFile()) {
940             return IGsiService::INSTALL_ERROR_GENERIC;
941         }
942         return IGsiService::INSTALL_OK;
943     }
944     if (!SetBootMode(one_shot) || !CreateInstallStatusFile()) {
945         return IGsiService::INSTALL_ERROR_GENERIC;
946     }
947     return IGsiService::INSTALL_OK;
948 }
949 
GetVoldService()950 static android::sp<android::os::IVold> GetVoldService() {
951     return android::waitForService<android::os::IVold>(android::String16("vold"));
952 }
953 
RemoveGsiFiles(const std::string & install_dir)954 bool GsiService::RemoveGsiFiles(const std::string& install_dir) {
955     bool ok = true;
956     auto active_dsu = GetDsuSlot(install_dir);
957     if (auto manager = ImageManager::Open(MetadataDir(active_dsu), install_dir)) {
958         std::vector<std::string> images = manager->GetAllBackingImages();
959         for (auto&& image : images) {
960             if (!android::base::EndsWith(image, kDsuPostfix)) {
961                 continue;
962             }
963             if (manager->IsImageMapped(image)) {
964                 ok &= manager->UnmapImageDevice(image);
965             }
966             ok &= manager->DeleteBackingImage(image);
967         }
968     }
969     auto dsu_slot = GetDsuSlot(install_dir);
970     std::vector<std::string> files{
971             kDsuInstallStatusFile,
972             kDsuOneShotBootFile,
973             DsuInstallDirFile(dsu_slot),
974             GetCompleteIndication(dsu_slot),
975     };
976     for (const auto& file : files) {
977         std::string message;
978         if (!RemoveFileIfExists(file, &message)) {
979             LOG(ERROR) << message;
980             ok = false;
981         }
982     }
983     if (auto vold = GetVoldService()) {
984         auto status = vold->destroyDsuMetadataKey(dsu_slot);
985         if (status.isOk()) {
986             std::string message;
987             if (!RemoveFileIfExists(DsuMetadataKeyDirFile(dsu_slot), &message)) {
988                 LOG(ERROR) << message;
989                 ok = false;
990             }
991         } else {
992             LOG(ERROR) << "Failed to destroy DSU metadata encryption key.";
993             ok = false;
994         }
995     } else {
996         LOG(ERROR) << "Failed to retrieve vold service.";
997         ok = false;
998     }
999     if (ok) {
1000         SetProperty(kGsiInstalledProp, "0");
1001     }
1002     return ok;
1003 }
1004 
DisableGsiInstall()1005 bool GsiService::DisableGsiInstall() {
1006     if (!android::gsi::IsGsiInstalled()) {
1007         LOG(ERROR) << "cannot disable gsi install - no install detected";
1008         return false;
1009     }
1010     if (installer_) {
1011         LOG(ERROR) << "cannot disable gsi during GSI installation";
1012         return false;
1013     }
1014     if (!DisableGsi()) {
1015         PLOG(ERROR) << "could not write gsi status";
1016         return false;
1017     }
1018     return true;
1019 }
1020 
GetCompleteIndication(const std::string & dsu_slot)1021 std::string GsiService::GetCompleteIndication(const std::string& dsu_slot) {
1022     return DSU_METADATA_PREFIX + dsu_slot + "/complete";
1023 }
1024 
IsInstallationComplete(const std::string & dsu_slot)1025 bool GsiService::IsInstallationComplete(const std::string& dsu_slot) {
1026     if (access(kDsuInstallStatusFile, F_OK) != 0) {
1027         return false;
1028     }
1029     std::string file = GetCompleteIndication(dsu_slot);
1030     std::string content;
1031     if (!ReadFileToString(file, &content)) {
1032         return false;
1033     }
1034     return content == "OK";
1035 }
1036 
GetInstalledDsuSlots()1037 std::vector<std::string> GsiService::GetInstalledDsuSlots() {
1038     std::vector<std::string> dsu_slots;
1039     auto d = std::unique_ptr<DIR, decltype(&closedir)>(opendir(DSU_METADATA_PREFIX), closedir);
1040     if (d != nullptr) {
1041         struct dirent* de;
1042         while ((de = readdir(d.get())) != nullptr) {
1043             if (de->d_name[0] == '.') {
1044                 continue;
1045             }
1046             auto dsu_slot = std::string(de->d_name);
1047             if (access(DsuInstallDirFile(dsu_slot).c_str(), F_OK) != 0) {
1048                 continue;
1049             }
1050             dsu_slots.push_back(dsu_slot);
1051         }
1052     }
1053     return dsu_slots;
1054 }
1055 
CleanCorruptedInstallation()1056 void GsiService::CleanCorruptedInstallation() {
1057     for (auto&& slot : GetInstalledDsuSlots()) {
1058         bool is_complete = IsInstallationComplete(slot);
1059         if (!is_complete) {
1060             LOG(INFO) << "CleanCorruptedInstallation for slot: " << slot;
1061             std::string install_dir;
1062             if (!android::base::ReadFileToString(DsuInstallDirFile(slot), &install_dir) ||
1063                 !RemoveGsiFiles(install_dir)) {
1064                 LOG(ERROR) << "Failed to CleanCorruptedInstallation on " << slot;
1065             }
1066         }
1067     }
1068 }
1069 
RunStartupTasks()1070 void GsiService::RunStartupTasks() {
1071     CleanCorruptedInstallation();
1072 
1073     std::string active_dsu;
1074     if (!GetActiveDsu(&active_dsu)) {
1075         PLOG(INFO) << "no DSU";
1076         return;
1077     }
1078     std::string boot_key;
1079     if (!GetInstallStatus(&boot_key)) {
1080         PLOG(ERROR) << "read " << kDsuInstallStatusFile;
1081         return;
1082     }
1083 
1084     if (!IsGsiRunning()) {
1085         // Check if a wipe was requested from fastboot or adb-in-gsi.
1086         if (boot_key == kInstallStatusWipe) {
1087             RemoveGsiFiles(GetInstalledImageDir());
1088         }
1089     } else {
1090         // NB: When single-boot is enabled, init will write "disabled" into the
1091         // install_status file, which will cause GetBootAttempts to return
1092         // false. Thus, we won't write "ok" here.
1093         int ignore;
1094         if (GetBootAttempts(boot_key, &ignore)) {
1095             // Mark the GSI as having successfully booted.
1096             if (!android::base::WriteStringToFile(kInstallStatusOk, kDsuInstallStatusFile)) {
1097                 PLOG(ERROR) << "write " << kDsuInstallStatusFile;
1098             }
1099         }
1100     }
1101 }
1102 
GetAvbPublicKeyFromFd(int fd,AvbPublicKey * dst)1103 static bool GetAvbPublicKeyFromFd(int fd, AvbPublicKey* dst) {
1104     // Read the AVB footer from EOF.
1105     int64_t total_size = get_block_device_size(fd);
1106     int64_t footer_offset = total_size - AVB_FOOTER_SIZE;
1107     std::array<uint8_t, AVB_FOOTER_SIZE> footer_bytes;
1108     if (!ReadFullyAtOffset(fd, footer_bytes.data(), AVB_FOOTER_SIZE, footer_offset)) {
1109         PLOG(ERROR) << "cannot read AVB footer";
1110         return false;
1111     }
1112     // Validate the AVB footer data and byte swap to native byte order.
1113     AvbFooter footer;
1114     if (!avb_footer_validate_and_byteswap((const AvbFooter*)footer_bytes.data(), &footer)) {
1115         LOG(ERROR) << "invalid AVB footer";
1116         return false;
1117     }
1118     // Read the VBMeta image.
1119     std::vector<uint8_t> vbmeta_bytes(footer.vbmeta_size);
1120     if (!ReadFullyAtOffset(fd, vbmeta_bytes.data(), vbmeta_bytes.size(), footer.vbmeta_offset)) {
1121         PLOG(ERROR) << "cannot read VBMeta image";
1122         return false;
1123     }
1124     // Validate the VBMeta image and retrieve AVB public key.
1125     // After a successful call to avb_vbmeta_image_verify(), public_key_data
1126     // will point to the serialized AVB public key, in the same format generated
1127     // by the `avbtool extract_public_key` command.
1128     const uint8_t* public_key_data;
1129     size_t public_key_size;
1130     AvbVBMetaVerifyResult result = avb_vbmeta_image_verify(vbmeta_bytes.data(), vbmeta_bytes.size(),
1131                                                            &public_key_data, &public_key_size);
1132     if (result != AVB_VBMETA_VERIFY_RESULT_OK) {
1133         LOG(ERROR) << "invalid VBMeta image: " << avb_vbmeta_verify_result_to_string(result);
1134         return false;
1135     }
1136     if (public_key_data != nullptr) {
1137         dst->bytes.resize(public_key_size);
1138         memcpy(dst->bytes.data(), public_key_data, public_key_size);
1139         dst->sha1.resize(SHA_DIGEST_LENGTH);
1140         SHA1(public_key_data, public_key_size, dst->sha1.data());
1141     }
1142     return true;
1143 }
1144 
1145 }  // namespace gsi
1146 }  // namespace android
1147