2 * Copyright (C) 2017 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
19 #include "VoldNativeService.h"
20 #include "Benchmark.h"
21 #include "CheckEncryption.h"
22 #include "IdleMaint.h"
23 #include "MoveStorage.h"
25 #include "VolumeManager.h"
28 #include "Ext4Crypt.h"
29 #include "MetadataCrypt.h"
34 #include <android-base/logging.h>
35 #include <android-base/stringprintf.h>
36 #include <android-base/strings.h>
37 #include <ext4_utils/ext4_crypt.h>
39 #include <private/android_filesystem_config.h>
40 #include <utils/Trace.h>
42 using android::base::StringPrintf;
50 constexpr const char* kDump = "android.permission.DUMP";
52 static binder::Status ok() {
53 return binder::Status::ok();
56 static binder::Status exception(uint32_t code, const std::string& msg) {
57 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
60 static binder::Status error(const std::string& msg) {
62 return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
65 static binder::Status translate(int status) {
67 return binder::Status::ok();
69 return binder::Status::fromServiceSpecificError(status);
73 static binder::Status translateBool(bool status) {
75 return binder::Status::ok();
77 return binder::Status::fromServiceSpecificError(status);
81 binder::Status checkPermission(const char* permission) {
85 if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
86 reinterpret_cast<int32_t*>(&uid))) {
89 return exception(binder::Status::EX_SECURITY,
90 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
94 binder::Status checkUid(uid_t expectedUid) {
95 uid_t uid = IPCThreadState::self()->getCallingUid();
96 if (uid == expectedUid || uid == AID_ROOT) {
99 return exception(binder::Status::EX_SECURITY,
100 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
104 binder::Status checkArgumentId(const std::string& id) {
106 return exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Missing ID");
108 for (const char& c : id) {
109 if (!std::isalnum(c) && c != ':' && c != ',') {
110 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
111 StringPrintf("ID %s is malformed", id.c_str()));
117 binder::Status checkArgumentPath(const std::string& path) {
119 return exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Missing path");
121 if (path[0] != '/') {
122 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
123 StringPrintf("Path %s is relative", path.c_str()));
125 if ((path + '/').find("/../") != std::string::npos) {
126 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
127 StringPrintf("Path %s is shady", path.c_str()));
129 for (const char& c : path) {
130 if (c == '\0' || c == '\n') {
131 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
132 StringPrintf("Path %s is malformed", path.c_str()));
138 binder::Status checkArgumentHex(const std::string& hex) {
139 // Empty hex strings are allowed
140 for (const char& c : hex) {
141 if (!std::isxdigit(c) && c != ':' && c != '-') {
142 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
143 StringPrintf("Hex %s is malformed", hex.c_str()));
149 #define ENFORCE_UID(uid) { \
150 binder::Status status = checkUid((uid)); \
151 if (!status.isOk()) { \
156 #define CHECK_ARGUMENT_ID(id) { \
157 binder::Status status = checkArgumentId((id)); \
158 if (!status.isOk()) { \
163 #define CHECK_ARGUMENT_PATH(path) { \
164 binder::Status status = checkArgumentPath((path)); \
165 if (!status.isOk()) { \
170 #define CHECK_ARGUMENT_HEX(hex) { \
171 binder::Status status = checkArgumentHex((hex)); \
172 if (!status.isOk()) { \
177 #define ACQUIRE_LOCK \
178 std::lock_guard<std::mutex> lock(VolumeManager::Instance()->getLock()); \
181 #define ACQUIRE_CRYPT_LOCK \
182 std::lock_guard<std::mutex> lock(VolumeManager::Instance()->getCryptLock()); \
187 status_t VoldNativeService::start() {
188 IPCThreadState::self()->disableBackgroundScheduling(true);
189 status_t ret = BinderService<VoldNativeService>::publish();
190 if (ret != android::OK) {
193 sp<ProcessState> ps(ProcessState::self());
194 ps->startThreadPool();
195 ps->giveThreadPoolName();
199 status_t VoldNativeService::dump(int fd, const Vector<String16> & /* args */) {
200 auto out = std::fstream(StringPrintf("/proc/self/fd/%d", fd));
201 const binder::Status dump_permission = checkPermission(kDump);
202 if (!dump_permission.isOk()) {
203 out << dump_permission.toString8() << endl;
204 return PERMISSION_DENIED;
208 out << "vold is happy!" << endl;
213 binder::Status VoldNativeService::setListener(
214 const android::sp<android::os::IVoldListener>& listener) {
215 ENFORCE_UID(AID_SYSTEM);
218 VolumeManager::Instance()->setListener(listener);
222 binder::Status VoldNativeService::monitor() {
223 ENFORCE_UID(AID_SYSTEM);
225 // Simply acquire/release each lock for watchdog
236 binder::Status VoldNativeService::reset() {
237 ENFORCE_UID(AID_SYSTEM);
240 return translate(VolumeManager::Instance()->reset());
243 binder::Status VoldNativeService::shutdown() {
244 ENFORCE_UID(AID_SYSTEM);
247 return translate(VolumeManager::Instance()->shutdown());
250 binder::Status VoldNativeService::onUserAdded(int32_t userId, int32_t userSerial) {
251 ENFORCE_UID(AID_SYSTEM);
254 return translate(VolumeManager::Instance()->onUserAdded(userId, userSerial));
257 binder::Status VoldNativeService::onUserRemoved(int32_t userId) {
258 ENFORCE_UID(AID_SYSTEM);
261 return translate(VolumeManager::Instance()->onUserRemoved(userId));
264 binder::Status VoldNativeService::onUserStarted(int32_t userId) {
265 ENFORCE_UID(AID_SYSTEM);
268 return translate(VolumeManager::Instance()->onUserStarted(userId));
271 binder::Status VoldNativeService::onUserStopped(int32_t userId) {
272 ENFORCE_UID(AID_SYSTEM);
275 return translate(VolumeManager::Instance()->onUserStopped(userId));
278 binder::Status VoldNativeService::onSecureKeyguardStateChanged(bool isShowing) {
279 ENFORCE_UID(AID_SYSTEM);
282 return translate(VolumeManager::Instance()->onSecureKeyguardStateChanged(isShowing));
285 binder::Status VoldNativeService::partition(const std::string& diskId, int32_t partitionType,
287 ENFORCE_UID(AID_SYSTEM);
288 CHECK_ARGUMENT_ID(diskId);
291 auto disk = VolumeManager::Instance()->findDisk(diskId);
292 if (disk == nullptr) {
293 return error("Failed to find disk " + diskId);
295 switch (partitionType) {
296 case PARTITION_TYPE_PUBLIC: return translate(disk->partitionPublic());
297 case PARTITION_TYPE_PRIVATE: return translate(disk->partitionPrivate());
298 case PARTITION_TYPE_MIXED: return translate(disk->partitionMixed(ratio));
299 default: return error("Unknown type " + std::to_string(partitionType));
303 binder::Status VoldNativeService::forgetPartition(const std::string& partGuid,
304 const std::string& fsUuid) {
305 ENFORCE_UID(AID_SYSTEM);
306 CHECK_ARGUMENT_HEX(partGuid);
307 CHECK_ARGUMENT_HEX(fsUuid);
310 return translate(VolumeManager::Instance()->forgetPartition(partGuid, fsUuid));
313 binder::Status VoldNativeService::mount(const std::string& volId, int32_t mountFlags,
314 int32_t mountUserId) {
315 ENFORCE_UID(AID_SYSTEM);
316 CHECK_ARGUMENT_ID(volId);
319 auto vol = VolumeManager::Instance()->findVolume(volId);
320 if (vol == nullptr) {
321 return error("Failed to find volume " + volId);
324 vol->setMountFlags(mountFlags);
325 vol->setMountUserId(mountUserId);
327 int res = vol->mount();
328 if ((mountFlags & MOUNT_FLAG_PRIMARY) != 0) {
329 VolumeManager::Instance()->setPrimary(vol);
331 return translate(res);
334 binder::Status VoldNativeService::unmount(const std::string& volId) {
335 ENFORCE_UID(AID_SYSTEM);
336 CHECK_ARGUMENT_ID(volId);
339 auto vol = VolumeManager::Instance()->findVolume(volId);
340 if (vol == nullptr) {
341 return error("Failed to find volume " + volId);
343 return translate(vol->unmount());
346 binder::Status VoldNativeService::format(const std::string& volId, const std::string& fsType) {
347 ENFORCE_UID(AID_SYSTEM);
348 CHECK_ARGUMENT_ID(volId);
351 auto vol = VolumeManager::Instance()->findVolume(volId);
352 if (vol == nullptr) {
353 return error("Failed to find volume " + volId);
355 return translate(vol->format(fsType));
358 static binder::Status pathForVolId(const std::string& volId, std::string* path) {
359 if (volId == "private" || volId == "null") {
362 auto vol = VolumeManager::Instance()->findVolume(volId);
363 if (vol == nullptr) {
364 return error("Failed to find volume " + volId);
366 if (vol->getType() != VolumeBase::Type::kPrivate) {
367 return error("Volume " + volId + " not private");
369 if (vol->getState() != VolumeBase::State::kMounted) {
370 return error("Volume " + volId + " not mounted");
372 *path = vol->getPath();
374 return error("Volume " + volId + " missing path");
380 binder::Status VoldNativeService::benchmark(
381 const std::string& volId, const android::sp<android::os::IVoldTaskListener>& listener) {
382 ENFORCE_UID(AID_SYSTEM);
383 CHECK_ARGUMENT_ID(volId);
387 auto status = pathForVolId(volId, &path);
388 if (!status.isOk()) return status;
391 android::vold::Benchmark(path, listener);
396 binder::Status VoldNativeService::checkEncryption(const std::string& volId) {
397 ENFORCE_UID(AID_SYSTEM);
398 CHECK_ARGUMENT_ID(volId);
402 auto status = pathForVolId(volId, &path);
403 if (!status.isOk()) return status;
404 return translate(android::vold::CheckEncryption(path));
407 binder::Status VoldNativeService::moveStorage(const std::string& fromVolId,
408 const std::string& toVolId, const android::sp<android::os::IVoldTaskListener>& listener) {
409 ENFORCE_UID(AID_SYSTEM);
410 CHECK_ARGUMENT_ID(fromVolId);
411 CHECK_ARGUMENT_ID(toVolId);
414 auto fromVol = VolumeManager::Instance()->findVolume(fromVolId);
415 auto toVol = VolumeManager::Instance()->findVolume(toVolId);
416 if (fromVol == nullptr) {
417 return error("Failed to find volume " + fromVolId);
418 } else if (toVol == nullptr) {
419 return error("Failed to find volume " + toVolId);
423 android::vold::MoveStorage(fromVol, toVol, listener);
428 binder::Status VoldNativeService::remountUid(int32_t uid, int32_t remountMode) {
429 ENFORCE_UID(AID_SYSTEM);
433 switch (remountMode) {
434 case REMOUNT_MODE_NONE: tmp = "none"; break;
435 case REMOUNT_MODE_DEFAULT: tmp = "default"; break;
436 case REMOUNT_MODE_READ: tmp = "read"; break;
437 case REMOUNT_MODE_WRITE: tmp = "write"; break;
438 default: return error("Unknown mode " + std::to_string(remountMode));
440 return translate(VolumeManager::Instance()->remountUid(uid, tmp));
443 binder::Status VoldNativeService::mkdirs(const std::string& path) {
444 ENFORCE_UID(AID_SYSTEM);
445 CHECK_ARGUMENT_PATH(path);
448 return translate(VolumeManager::Instance()->mkdirs(path));
451 binder::Status VoldNativeService::createObb(const std::string& sourcePath,
452 const std::string& sourceKey, int32_t ownerGid, std::string* _aidl_return) {
453 ENFORCE_UID(AID_SYSTEM);
454 CHECK_ARGUMENT_PATH(sourcePath);
455 CHECK_ARGUMENT_HEX(sourceKey);
459 VolumeManager::Instance()->createObb(sourcePath, sourceKey, ownerGid, _aidl_return));
462 binder::Status VoldNativeService::destroyObb(const std::string& volId) {
463 ENFORCE_UID(AID_SYSTEM);
464 CHECK_ARGUMENT_ID(volId);
467 return translate(VolumeManager::Instance()->destroyObb(volId));
470 binder::Status VoldNativeService::fstrim(int32_t fstrimFlags,
471 const android::sp<android::os::IVoldTaskListener>& listener) {
472 ENFORCE_UID(AID_SYSTEM);
476 android::vold::Trim(listener);
481 binder::Status VoldNativeService::runIdleMaint(
482 const android::sp<android::os::IVoldTaskListener>& listener) {
483 ENFORCE_UID(AID_SYSTEM);
487 android::vold::RunIdleMaint(listener);
492 binder::Status VoldNativeService::abortIdleMaint(
493 const android::sp<android::os::IVoldTaskListener>& listener) {
494 ENFORCE_UID(AID_SYSTEM);
498 android::vold::AbortIdleMaint(listener);
503 binder::Status VoldNativeService::mountAppFuse(int32_t uid, int32_t pid, int32_t mountId,
504 android::base::unique_fd* _aidl_return) {
505 ENFORCE_UID(AID_SYSTEM);
508 return translate(VolumeManager::Instance()->mountAppFuse(uid, pid, mountId, _aidl_return));
511 binder::Status VoldNativeService::unmountAppFuse(int32_t uid, int32_t pid, int32_t mountId) {
512 ENFORCE_UID(AID_SYSTEM);
515 return translate(VolumeManager::Instance()->unmountAppFuse(uid, pid, mountId));
518 binder::Status VoldNativeService::fdeCheckPassword(const std::string& password) {
519 ENFORCE_UID(AID_SYSTEM);
522 return translate(cryptfs_check_passwd(password.c_str()));
525 binder::Status VoldNativeService::fdeRestart() {
526 ENFORCE_UID(AID_SYSTEM);
529 // Spawn as thread so init can issue commands back to vold without
530 // causing deadlock, usually as a result of prep_data_fs.
531 std::thread(&cryptfs_restart).detach();
535 binder::Status VoldNativeService::fdeComplete(int32_t* _aidl_return) {
536 ENFORCE_UID(AID_SYSTEM);
539 *_aidl_return = cryptfs_crypto_complete();
543 static int fdeEnableInternal(int32_t passwordType, const std::string& password,
544 int32_t encryptionFlags) {
545 bool noUi = (encryptionFlags & VoldNativeService::ENCRYPTION_FLAG_NO_UI) != 0;
547 for (int tries = 0; tries < 2; ++tries) {
549 if (passwordType == VoldNativeService::PASSWORD_TYPE_DEFAULT) {
550 rc = cryptfs_enable_default(noUi);
552 rc = cryptfs_enable(passwordType, password.c_str(), noUi);
557 } else if (tries == 0) {
558 KillProcessesWithOpenFiles(DATA_MNT_POINT, SIGKILL);
565 binder::Status VoldNativeService::fdeEnable(int32_t passwordType,
566 const std::string& password, int32_t encryptionFlags) {
567 ENFORCE_UID(AID_SYSTEM);
570 LOG(DEBUG) << "fdeEnable(" << passwordType << ", *, " << encryptionFlags << ")";
571 if (e4crypt_is_native()) {
572 LOG(ERROR) << "e4crypt_is_native, fdeEnable invalid";
573 return error("e4crypt_is_native, fdeEnable invalid");
575 LOG(DEBUG) << "!e4crypt_is_native, spawning fdeEnableInternal";
577 // Spawn as thread so init can issue commands back to vold without
578 // causing deadlock, usually as a result of prep_data_fs.
579 std::thread(&fdeEnableInternal, passwordType, password, encryptionFlags).detach();
583 binder::Status VoldNativeService::fdeChangePassword(int32_t passwordType,
584 const std::string& password) {
585 ENFORCE_UID(AID_SYSTEM);
588 return translate(cryptfs_changepw(passwordType, password.c_str()));
591 binder::Status VoldNativeService::fdeVerifyPassword(const std::string& password) {
592 ENFORCE_UID(AID_SYSTEM);
595 return translate(cryptfs_verify_passwd(password.c_str()));
598 binder::Status VoldNativeService::fdeGetField(const std::string& key,
599 std::string* _aidl_return) {
600 ENFORCE_UID(AID_SYSTEM);
603 char buf[PROPERTY_VALUE_MAX];
604 if (cryptfs_getfield(key.c_str(), buf, sizeof(buf)) != CRYPTO_GETFIELD_OK) {
605 return error(StringPrintf("Failed to read field %s", key.c_str()));
612 binder::Status VoldNativeService::fdeSetField(const std::string& key,
613 const std::string& value) {
614 ENFORCE_UID(AID_SYSTEM);
617 return translate(cryptfs_setfield(key.c_str(), value.c_str()));
620 binder::Status VoldNativeService::fdeGetPasswordType(int32_t* _aidl_return) {
621 ENFORCE_UID(AID_SYSTEM);
624 *_aidl_return = cryptfs_get_password_type();
628 binder::Status VoldNativeService::fdeGetPassword(std::string* _aidl_return) {
629 ENFORCE_UID(AID_SYSTEM);
632 const char* res = cryptfs_get_password();
633 if (res != nullptr) {
639 binder::Status VoldNativeService::fdeClearPassword() {
640 ENFORCE_UID(AID_SYSTEM);
643 cryptfs_clear_password();
647 binder::Status VoldNativeService::fbeEnable() {
648 ENFORCE_UID(AID_SYSTEM);
651 return translateBool(e4crypt_initialize_global_de());
654 binder::Status VoldNativeService::mountDefaultEncrypted() {
655 ENFORCE_UID(AID_SYSTEM);
658 if (!e4crypt_is_native()) {
659 // Spawn as thread so init can issue commands back to vold without
660 // causing deadlock, usually as a result of prep_data_fs.
661 std::thread(&cryptfs_mount_default_encrypted).detach();
666 binder::Status VoldNativeService::initUser0() {
667 ENFORCE_UID(AID_SYSTEM);
670 return translateBool(e4crypt_init_user0());
673 binder::Status VoldNativeService::isConvertibleToFbe(bool* _aidl_return) {
674 ENFORCE_UID(AID_SYSTEM);
677 *_aidl_return = cryptfs_isConvertibleToFBE() != 0;
681 binder::Status VoldNativeService::mountFstab(const std::string& mountPoint) {
682 ENFORCE_UID(AID_SYSTEM);
685 return translateBool(e4crypt_mount_metadata_encrypted(mountPoint, false));
688 binder::Status VoldNativeService::encryptFstab(const std::string& mountPoint) {
689 ENFORCE_UID(AID_SYSTEM);
692 return translateBool(e4crypt_mount_metadata_encrypted(mountPoint, true));
695 binder::Status VoldNativeService::createUserKey(int32_t userId, int32_t userSerial,
697 ENFORCE_UID(AID_SYSTEM);
700 return translateBool(e4crypt_vold_create_user_key(userId, userSerial, ephemeral));
703 binder::Status VoldNativeService::destroyUserKey(int32_t userId) {
704 ENFORCE_UID(AID_SYSTEM);
707 return translateBool(e4crypt_destroy_user_key(userId));
710 binder::Status VoldNativeService::addUserKeyAuth(int32_t userId, int32_t userSerial,
711 const std::string& token, const std::string& secret) {
712 ENFORCE_UID(AID_SYSTEM);
715 return translateBool(e4crypt_add_user_key_auth(userId, userSerial, token, secret));
718 binder::Status VoldNativeService::fixateNewestUserKeyAuth(int32_t userId) {
719 ENFORCE_UID(AID_SYSTEM);
722 return translateBool(e4crypt_fixate_newest_user_key_auth(userId));
725 binder::Status VoldNativeService::unlockUserKey(int32_t userId, int32_t userSerial,
726 const std::string& token, const std::string& secret) {
727 ENFORCE_UID(AID_SYSTEM);
730 return translateBool(e4crypt_unlock_user_key(userId, userSerial, token, secret));
733 binder::Status VoldNativeService::lockUserKey(int32_t userId) {
734 ENFORCE_UID(AID_SYSTEM);
737 return translateBool(e4crypt_lock_user_key(userId));
740 binder::Status VoldNativeService::prepareUserStorage(const std::unique_ptr<std::string>& uuid,
741 int32_t userId, int32_t userSerial, int32_t flags) {
742 ENFORCE_UID(AID_SYSTEM);
743 std::string empty_string = "";
744 auto uuid_ = uuid ? *uuid : empty_string;
745 CHECK_ARGUMENT_HEX(uuid_);
748 return translateBool(e4crypt_prepare_user_storage(uuid_, userId, userSerial, flags));
751 binder::Status VoldNativeService::destroyUserStorage(const std::unique_ptr<std::string>& uuid,
752 int32_t userId, int32_t flags) {
753 ENFORCE_UID(AID_SYSTEM);
754 std::string empty_string = "";
755 auto uuid_ = uuid ? *uuid : empty_string;
756 CHECK_ARGUMENT_HEX(uuid_);
759 return translateBool(e4crypt_destroy_user_storage(uuid_, userId, flags));
763 } // namespace android