2 * Copyright (c) 2015-2019 Samsung Electronics Co., Ltd All Rights Reserved
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
20 #include <condition_variable>
27 #include <sys/mount.h>
28 #include <sys/reboot.h>
35 #include <tzplatform_config.h>
36 #include <device/power.h>
37 #include <klay/process.h>
38 #include <klay/file-user.h>
39 #include <klay/filesystem.h>
40 #include <klay/dbus/connection.h>
41 #include <klay/dbus/signal.h>
42 #include <klay/error.h>
43 #include <systemd/sd-bus.h>
47 #include "progress-bar.h"
48 #include "rmi/common.h"
50 #include "ext4-tool.h"
51 #include "internal-encryption.h"
52 #include "internal-encryption-common.h"
53 #include "upgrade-support.h"
54 #include "file-footer.h"
60 const char *PRIVILEGE_PLATFORM = "http://tizen.org/privilege/internal/default/platform";
61 const std::string ODE_OBJECT_PATH = "/Org/Tizen/OnDeviceEncryption";
62 const std::string ODE_INTERFACE_EVENT = "org.tizen.OnDeviceEncryption.Event";
63 const std::string ODE_SIGNAL_NAME = "unmount";
64 const std::string manifest =
66 " <interface name='" + ODE_INTERFACE_EVENT + "'>"
67 " <signal name='" + ODE_SIGNAL_NAME + "'>"
72 // watches systemd jobs
75 explicit JobWatch(dbus::Connection& systemDBus);
78 bool waitForJob(const std::string& job);
81 void jobRemoved(const dbus::Variant& parameters);
85 const std::string& job,
86 const std::string& unit,
87 const std::string& result) : id(id), job(job), unit(unit), result(result) {}
94 dbus::Connection::SubscriptionId id;
95 dbus::Connection& systemDBus;
96 std::list<Job> removedJobs;
98 std::condition_variable jobsCv;
101 JobWatch::JobWatch(dbus::Connection& systemDBus) : systemDBus(systemDBus) {
102 auto callback = [this](dbus::Variant parameters) {
103 this->jobRemoved(parameters);
106 id = systemDBus.subscribeSignal("",
107 "/org/freedesktop/systemd1",
108 "org.freedesktop.systemd1.Manager",
113 JobWatch::~JobWatch() {
114 systemDBus.unsubscribeSignal(id);
117 bool JobWatch::waitForJob(const std::string& job) {
119 std::unique_lock<std::mutex> lock(jobsMutex);
121 auto sec = std::chrono::seconds(1);
122 jobsCv.wait_for(lock, 5*sec, [this, &timeout]{
123 if (!removedJobs.empty()) {
130 ERROR(SINK, "job: " + job + ", result: time out");
134 while(!removedJobs.empty()) {
135 bool match = (removedJobs.front().job == job);
136 bool done = (removedJobs.front().result == "done");
137 removedJobs.pop_front();
144 void JobWatch::jobRemoved(const dbus::Variant& parameters)
150 parameters.get("(uoss)", &id, &job, &unit, &result);
151 WARN(SINK, "id:" + std::to_string(id) + " job:" + job + " unit:" + unit + " result:" + result);
154 std::lock_guard<std::mutex> guard(jobsMutex);
155 removedJobs.emplace_back(id, job, unit, result);
160 void stopSystemdUnits()
162 dbus::Connection& systemDBus = dbus::Connection::getSystem();
163 dbus::VariantIterator iter;
164 std::vector<std::string> preprocessUnits;
165 std::set<std::string> unitsToStop;
168 systemDBus.emitSignal("",
171 ODE_SIGNAL_NAME, "()", nullptr);
172 } catch (runtime::Exception &e) {
173 ERROR(SINK, "Failed to emit signal : " + std::string(e.what()));
176 auto stopUnit = [&systemDBus](const std::string &unit) {
177 JobWatch watch(systemDBus);
178 WARN(SINK, "Stopping unit: " + unit);
179 const char* job = NULL;
181 systemDBus.methodcall("org.freedesktop.systemd1",
182 "/org/freedesktop/systemd1",
183 "org.freedesktop.systemd1.Manager",
185 -1, "(o)", "(ss)", unit.c_str(), "flush").get("(o)", &job);
186 WARN(SINK, "Waiting for job: " + std::string(job));
187 if (!watch.waitForJob(job))
188 ERROR(SINK, "Stopping unit: " + unit + " failed");
189 } catch (runtime::Exception &e) {
190 ERROR(SINK, std::string(e.what()));
195 systemDBus.methodcall("org.freedesktop.systemd1",
196 "/org/freedesktop/systemd1",
197 "org.freedesktop.systemd1.Manager",
199 -1, "(a(ssssssouso))", "").get("(a(ssssssouso))", &iter);
200 } catch (runtime::Exception &e) {
201 ERROR(SINK, "Get list of systemd unit : " + std::string(e.what()));
205 unsigned int dataUnit;
208 ret = iter.get("(ssssssouso)", dataStr, dataStr + 1, dataStr + 2,
209 dataStr + 3, dataStr + 4, dataStr + 5,
210 dataStr + 6, &dataUnit, dataStr + 7, dataStr + 8);
214 std::string unitName(dataStr[0]);
215 if (unitName == "security-manager.socket" ||
216 unitName == "connman.socket" ||
217 unitName == "msg-server.socket") {
218 preprocessUnits.insert(preprocessUnits.begin(), unitName);
219 } else if (unitName.compare(0, 5, "user@") == 0 ||
220 unitName == "tlm.service" ||
221 unitName == "resourced.service" ||
222 unitName == "security-manager.service") {
223 preprocessUnits.push_back(unitName);
227 for (auto unit : preprocessUnits) {
231 for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
232 auto pgid = ::getpgid(pid);
233 if (pgid > 0 && pid != pgid) {
234 WARN(SINK, "PGID doesn't match - pgid : " + std::to_string(pgid) + ", pid : " + std::to_string(pid));
239 char *unit = nullptr;
240 systemDBus.methodcall("org.freedesktop.systemd1",
241 "/org/freedesktop/systemd1",
242 "org.freedesktop.systemd1.Manager",
244 -1, "(o)", "(u)", (unsigned int)pid)
248 int err = sd_bus_path_decode(unit, "/org/freedesktop/systemd1/unit", &tmp);
249 if (err <= 0 || tmp == NULL) {
250 ERROR(SINK, "Failed to decode unit name: " + std::string(unit) + " error: " +
251 std::to_string(err));
254 std::string unescapedName(tmp);
257 unitsToStop.insert(unescapedName);
258 } catch (runtime::Exception &e) {
259 ERROR(SINK, "Killing process: " + std::to_string(pid));
260 ::kill(pid, SIGKILL);
264 for (auto unit : unitsToStop) {
269 void showProgressUI(const std::string type)
271 dbus::Connection& systemDBus = dbus::Connection::getSystem();
272 std::string unit("ode-progress-ui@"+type+".service");
274 JobWatch watch(systemDBus);
275 INFO(SINK, "Start unit: " + unit);
277 const char* job = NULL;
278 systemDBus.methodcall("org.freedesktop.systemd1",
279 "/org/freedesktop/systemd1",
280 "org.freedesktop.systemd1.Manager",
282 -1, "(o)", "(ss)", unit.c_str(), "replace").get("(o)", &job);
284 INFO(SINK, "Waiting for job: " + std::string(job));
285 if (!watch.waitForJob(job))
286 ERROR(SINK, "Starting unit: " + unit + " failed");
289 unsigned int getOptions()
291 unsigned int result = 0;
295 ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
297 result |= InternalEncryption::Option::IncludeUnusedRegion;
303 void setOptions(unsigned int options)
307 if (options & InternalEncryption::Option::IncludeUnusedRegion) {
312 ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
315 void killProcesses(std::vector<const char*> &args)
317 int pipeFd[2] = {0, };
320 if (::pipe(pipeFd) < 0)
321 throw runtime::Exception("Failed to create pipe");
327 throw runtime::Exception("Failed to fork");
332 if (::dup2(pipeFd[1], STDOUT_FILENO) < 0)
333 ERROR(SINK, "Failed to copy STDOUT_FILENO");
335 if (::dup2(STDOUT_FILENO, STDERR_FILENO) < 0)
336 ERROR(SINK, "Failed to copy STDERR_FILENO");
340 if (::execv(args[0], const_cast<char* const*>(args.data())) < 0)
341 ERROR(SINK, "Failed to execute : " + std::to_string(errno));
343 std::quick_exit(EXIT_FAILURE);
348 for (int status = 0; ::waitpid(pid, &status, 0) == -1;) {
349 if (errno != EINTR) {
351 throw runtime::Exception("Failed to wait child process");
355 auto closeFile = [](FILE *fp) { ::fclose(fp); };
356 std::unique_ptr<FILE, decltype(closeFile)> fp(::fdopen(pipeFd[0], "r"), closeFile);
359 throw runtime::Exception("Failed to open pipe descriptor");
362 char *line = nullptr;
365 while ((::getline(&line, &len, fp.get())) != -1) {
366 std::string log(line);
367 log.erase(std::find_if(log.rbegin(), log.rend(),
368 std::ptr_fun<int, int>(std::isgraph)).base(), log.end());
371 } catch (std::exception &e) {
372 ERROR(SINK, e.what());
378 bool isPartitionTerminated(const std::string &partition)
381 const std::string cmd("fuser -m " + partition + " | grep -o '[0-9]*'");
382 char *line = nullptr;
385 FILE *fp = ::popen(cmd.c_str(), "r");
387 ERROR(SINK, "Failed to get processes on partition");
391 if (::getline(&line, &len, fp) != -1)
400 void unmountInternalStorage(const std::string& source)
402 if (::umount2("/opt/usr", MNT_DETACH) == -1) {
403 if (errno != EBUSY && errno != EINVAL) {
404 throw runtime::Exception("umount() error : " + runtime::GetSystemErrorMessage());
410 std::vector<const char*> args = {
411 "/usr/bin/fuser", "-m", "-k", "-v", "-SIGTERM", source.c_str(), nullptr
415 ::usleep((useconds_t)((unsigned int)(500)*1000));
417 args[4] = "-SIGKILL";
419 ::usleep((useconds_t)((unsigned int)(200)*1000));
420 } catch (runtime::Exception &e) {
423 } while (!isPartitionTerminated(source));
428 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv,
433 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
434 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)(std::vector<unsigned char>, unsigned int));
435 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
436 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::isMounted)());
437 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
438 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
439 server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
440 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::recovery)());
441 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
442 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
443 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
444 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
445 server.expose(this, "", (int)(InternalEncryptionServer::getState)());
446 server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
447 server.expose(this, "", (std::string)(InternalEncryptionServer::getDevicePath)());
449 server.createNotification("InternalEncryptionServer::mount");
451 std::string source = findDevPath();
453 if (getState() == State::Encrypted) {
454 //"error_partially_encrypted"
455 if (!FileFooter::exist(source) && !UpgradeSupport::checkUpgradeFlag()) {
456 // Trigger key migration process
457 UpgradeSupport::createUpgradeFlag();
461 engine.reset(new INTERNAL_ENGINE(
462 source, INTERNAL_PATH,
463 ProgressBar([](int v) {
464 ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
465 std::to_string(v).c_str());
470 dbus::Connection &systemDBus = dbus::Connection::getSystem();
471 systemDBus.registerObject(ODE_OBJECT_PATH, manifest, nullptr, nullptr);
472 } catch (runtime::Exception &e) {
473 ERROR(SINK, e.what());
477 InternalEncryptionServer::~InternalEncryptionServer()
481 int InternalEncryptionServer::migrateMasterKey(const std::string& dev, const std::string& password)
484 BinaryData masterKey = UpgradeSupport::loadMasterKey(dev);
486 // encrypt the master key with given password
487 return keyServer.changePassword2(dev, masterKey, password);
488 } catch (const runtime::Exception&) {
489 ERROR(SINK, "Failed to load the master key stored during upgrade.");
492 return error::Unknown;
495 int InternalEncryptionServer::setMountPassword(const std::string& password)
497 const std::string& dev = engine->getSource();
499 // check if upgrade flag exists
500 if (UpgradeSupport::checkUpgradeFlag()) {
501 INFO(SINK, "Upgrade flag detected.");
503 int rc = migrateMasterKey(dev, password);
504 if (rc != error::None)
506 UpgradeSupport::removeUpgradeFlag();
509 return keyServer.get(dev, password, mountKey);
512 int InternalEncryptionServer::mount(const std::vector<unsigned char> &mk, unsigned int options)
514 if (mountKey.empty() && mk.empty()) {
515 ERROR(SINK, "You need to set master key first.");
516 return error::NoData;
519 BinaryData key = mk.empty() ? mountKey : mk;
522 if (getState() != State::Encrypted) {
523 ERROR(SINK, "Cannot mount, SD partition's state incorrect.");
524 return error::NoSuchDevice;
527 if (engine->isMounted()) {
528 ERROR(SINK, "Partition already mounted.");
532 INFO(SINK, "Mounting internal storage.");
534 engine->mount(key, getOptions());
536 server.notify("InternalEncryptionServer::mount");
538 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
539 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
540 } catch (runtime::Exception &e) {
541 ERROR(SINK, "Mount failed: " + std::string(e.what()));
542 return error::Unknown;
548 int InternalEncryptionServer::isMounted()
552 ret = engine->isMounted() ? 1 : 0;
553 } catch (runtime::Exception &e) {
554 ERROR(SINK, "Failed to access the mount flag");
555 return error::Unknown;
560 int InternalEncryptionServer::umount()
562 if (getState() != State::Encrypted) {
563 ERROR(SINK, "Cannot umount, partition's state incorrect.");
564 return error::NoSuchDevice;
567 if (!engine->isMounted()) {
568 ERROR(SINK, "Partition already umounted.");
572 INFO(SINK, "Closing all processes using internal storage.");
575 INFO(SINK, "Umounting internal storage.");
576 unmountInternalStorage("/dev/mapper/userdata");
578 } catch (runtime::Exception &e) {
579 ERROR(SINK, "Umount failed: " + std::string(e.what()));
580 return error::Unknown;
586 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
588 if (getState() != State::Unencrypted) {
589 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
590 return error::NoSuchDevice;
593 BinaryData masterKey;
594 int ret = keyServer.get(engine->getSource(), password, masterKey);
595 if (ret != error::None)
598 auto encryptWorker = [masterKey, options, this]() {
600 if (::device_power_request_lock(POWER_LOCK_DISPLAY, 0) != 0)
601 ERROR(SINK, "Failed to request to lock display");
603 showProgressUI("encrypt");
606 runtime::File file("/opt/etc/.odeprogress");
609 std::string source = engine->getSource();
610 auto mntPaths = findMountPointsByDevice(source);
612 if (!mntPaths.empty()) {
613 INFO(SINK, "Closing all processes using internal storage.");
616 INFO(SINK, "Unmounting internal storage.");
617 unmountInternalStorage(source);
620 INFO(SINK, "Encryption started.");
621 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
623 engine->encrypt(masterKey, options);
624 } catch (runtime::Exception &e) {
625 ERROR(SINK, e.what());
626 if (!engine->isStarted()) {
627 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
631 ::reboot(RB_AUTOBOOT);
633 setOptions(options & getSupportedOptions());
635 INFO(SINK, "Encryption completed.");
636 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
637 server.notify("InternalEncryptionServer::mount");
641 INFO(SINK, "Syncing disk and rebooting.");
643 ::reboot(RB_AUTOBOOT);
644 } catch (runtime::Exception &e) {
645 ERROR(SINK, "Encryption failed: " + std::string(e.what()));
649 std::thread asyncWork(encryptWorker);
655 int InternalEncryptionServer::decrypt(const std::string& password)
657 if (getState() != State::Encrypted) {
658 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
659 return error::NoSuchDevice;
662 // check if key migration is needed
663 if (UpgradeSupport::checkUpgradeFlag()) {
664 INFO(SINK, "Upgrade flag detected.");
665 const std::string& dev = engine->getSource();
666 int rc = migrateMasterKey(dev, password);
667 if (rc == error::None)
668 UpgradeSupport::removeUpgradeFlag();
671 BinaryData masterKey;
672 int ret = keyServer.get(engine->getSource(), password, masterKey);
673 if (ret != error::None)
676 auto decryptWorker = [masterKey, this]() {
678 if (::device_power_request_lock(POWER_LOCK_DISPLAY, 0) != 0)
679 ERROR(SINK, "Failed to request to lock display");
681 showProgressUI("decrypt");
684 runtime::File file("/opt/etc/.odeprogress");
687 if (engine->isMounted()) {
688 INFO(SINK, "Closing all processes using internal storage.");
691 INFO(SINK, "Umounting internal storage.");
692 unmountInternalStorage("/dev/mapper/userdata");
696 INFO(SINK, "Decryption started.");
697 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
699 engine->decrypt(masterKey, getOptions());
700 } catch (runtime::Exception &e) {
701 ERROR(SINK, e.what());
702 if (!engine->isStarted()) {
703 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
707 ::reboot(RB_AUTOBOOT);
710 INFO(SINK, "Decryption complete.");
711 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
715 INFO(SINK, "Syncing disk and rebooting.");
717 ::reboot(RB_AUTOBOOT);
718 } catch (runtime::Exception &e) {
719 ERROR(SINK, "Decryption failed: " + std::string(e.what()));
723 std::thread asyncWork(decryptWorker);
729 int InternalEncryptionServer::recovery()
731 int state = getState();
733 if (state == State::Unencrypted)
734 return error::NoSuchDevice;
736 runtime::File file("/opt/.factoryreset");
741 dbus::Connection& systemDBus = dbus::Connection::getSystem();
742 systemDBus.methodcall("org.tizen.system.deviced",
743 "/Org/Tizen/System/DeviceD/Power",
744 "org.tizen.system.deviced.power",
746 -1, "()", "(si)", "reboot", 0);
747 } catch (runtime::Exception &e) {
748 ::reboot(RB_AUTOBOOT);
753 int InternalEncryptionServer::isPasswordInitialized()
755 return keyServer.isInitialized(engine->getSource());
758 int InternalEncryptionServer::initPassword(const std::string& password)
760 return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
763 int InternalEncryptionServer::cleanPassword(const std::string& password)
765 return keyServer.remove(engine->getSource(), password);
768 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
769 const std::string& newPassword)
771 return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
774 int InternalEncryptionServer::verifyPassword(const std::string& password)
776 return keyServer.verifyPassword(engine->getSource(), password);
779 int InternalEncryptionServer::getState()
781 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
783 throw runtime::Exception("Failed to get vconf value.");
786 std::string valueStr(value);
789 if (valueStr == "encrypted")
790 return State::Encrypted;
791 else if (valueStr == "unencrypted")
792 return State::Unencrypted;
793 else if (valueStr == "error_partially_encrypted" || valueStr == "error_partially_decrypted")
794 return State::Corrupted;
796 return State::NotSupported;
799 unsigned int InternalEncryptionServer::getSupportedOptions()
801 return engine->getSupportedOptions();
804 std::string InternalEncryptionServer::getDevicePath() const
806 return engine->getSource();