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 mode_t MODE_0640 = S_IRUSR | S_IWUSR | S_IRGRP;
62 const std::string ODE_OBJECT_PATH = "/Org/Tizen/OnDeviceEncryption";
63 const std::string ODE_INTERFACE_EVENT = "org.tizen.OnDeviceEncryption.Event";
64 const std::string ODE_SIGNAL_NAME = "unmount";
65 const std::string manifest =
67 " <interface name='" + ODE_INTERFACE_EVENT + "'>"
68 " <signal name='" + ODE_SIGNAL_NAME + "'>"
73 // watches systemd jobs
76 explicit JobWatch(dbus::Connection& systemDBus);
79 bool waitForJob(const std::string& job);
82 void jobRemoved(const dbus::Variant& parameters);
86 const std::string& job,
87 const std::string& unit,
88 const std::string& result) : id(id), job(job), unit(unit), result(result) {}
95 dbus::Connection::SubscriptionId id;
96 dbus::Connection& systemDBus;
97 std::list<Job> removedJobs;
99 std::condition_variable jobsCv;
102 JobWatch::JobWatch(dbus::Connection& systemDBus) : systemDBus(systemDBus) {
103 auto callback = [this](dbus::Variant parameters) {
104 this->jobRemoved(parameters);
107 id = systemDBus.subscribeSignal("",
108 "/org/freedesktop/systemd1",
109 "org.freedesktop.systemd1.Manager",
114 JobWatch::~JobWatch() {
115 systemDBus.unsubscribeSignal(id);
118 bool JobWatch::waitForJob(const std::string& job) {
120 std::unique_lock<std::mutex> lock(jobsMutex);
122 auto sec = std::chrono::seconds(1);
123 jobsCv.wait_for(lock, 5*sec, [this, &timeout]{
124 if (!removedJobs.empty()) {
131 ERROR(SINK, "job: " + job + ", result: time out");
135 while(!removedJobs.empty()) {
136 bool match = (removedJobs.front().job == job);
137 bool done = (removedJobs.front().result == "done");
138 removedJobs.pop_front();
145 void JobWatch::jobRemoved(const dbus::Variant& parameters)
151 parameters.get("(uoss)", &id, &job, &unit, &result);
152 WARN(SINK, "id:" + std::to_string(id) + " job:" + job + " unit:" + unit + " result:" + result);
155 std::lock_guard<std::mutex> guard(jobsMutex);
156 removedJobs.emplace_back(id, job, unit, result);
161 void stopSystemdUnits()
163 dbus::Connection& systemDBus = dbus::Connection::getSystem();
164 dbus::VariantIterator iter;
165 std::vector<std::string> preprocessUnits;
166 std::set<std::string> unitsToStop;
169 systemDBus.emitSignal("",
172 ODE_SIGNAL_NAME, "()", nullptr);
173 } catch (runtime::Exception &e) {
174 ERROR(SINK, "Failed to emit signal : " + std::string(e.what()));
177 auto stopUnit = [&systemDBus](const std::string &unit) {
178 JobWatch watch(systemDBus);
179 WARN(SINK, "Stopping unit: " + unit);
180 const char* job = NULL;
182 systemDBus.methodcall("org.freedesktop.systemd1",
183 "/org/freedesktop/systemd1",
184 "org.freedesktop.systemd1.Manager",
186 -1, "(o)", "(ss)", unit.c_str(), "flush").get("(o)", &job);
187 WARN(SINK, "Waiting for job: " + std::string(job));
188 if (!watch.waitForJob(job))
189 ERROR(SINK, "Stopping unit: " + unit + " failed");
190 } catch (runtime::Exception &e) {
191 ERROR(SINK, std::string(e.what()));
196 systemDBus.methodcall("org.freedesktop.systemd1",
197 "/org/freedesktop/systemd1",
198 "org.freedesktop.systemd1.Manager",
200 -1, "(a(ssssssouso))", "").get("(a(ssssssouso))", &iter);
201 } catch (runtime::Exception &e) {
202 ERROR(SINK, "Get list of systemd unit : " + std::string(e.what()));
206 unsigned int dataUnit;
209 ret = iter.get("(ssssssouso)", dataStr, dataStr + 1, dataStr + 2,
210 dataStr + 3, dataStr + 4, dataStr + 5,
211 dataStr + 6, &dataUnit, dataStr + 7, dataStr + 8);
215 std::string unitName(dataStr[0]);
216 if (unitName == "security-manager.socket" ||
217 unitName == "connman.socket" ||
218 unitName == "msg-server.socket") {
219 preprocessUnits.insert(preprocessUnits.begin(), unitName);
220 } else if (unitName.compare(0, 5, "user@") == 0 ||
221 unitName == "tlm.service" ||
222 unitName == "resourced.service" ||
223 unitName == "security-manager.service") {
224 preprocessUnits.push_back(unitName);
228 for (auto unit : preprocessUnits) {
232 for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
233 auto pgid = ::getpgid(pid);
234 if (pgid > 0 && pid != pgid) {
235 WARN(SINK, "PGID doesn't match - pgid : " + std::to_string(pgid) + ", pid : " + std::to_string(pid));
240 char *unit = nullptr;
241 systemDBus.methodcall("org.freedesktop.systemd1",
242 "/org/freedesktop/systemd1",
243 "org.freedesktop.systemd1.Manager",
245 -1, "(o)", "(u)", (unsigned int)pid)
249 int err = sd_bus_path_decode(unit, "/org/freedesktop/systemd1/unit", &tmp);
250 if (err <= 0 || tmp == NULL) {
251 ERROR(SINK, "Failed to decode unit name: " + std::string(unit) + " error: " +
252 std::to_string(err));
255 std::string unescapedName(tmp);
258 unitsToStop.insert(unescapedName);
259 } catch (runtime::Exception &e) {
260 ERROR(SINK, "Killing process: " + std::to_string(pid));
261 ::kill(pid, SIGKILL);
265 for (auto unit : unitsToStop) {
270 void showProgressUI(const std::string type)
272 dbus::Connection& systemDBus = dbus::Connection::getSystem();
273 std::string unit("ode-progress-ui@"+type+".service");
275 JobWatch watch(systemDBus);
276 INFO(SINK, "Start unit: " + unit);
278 const char* job = NULL;
279 systemDBus.methodcall("org.freedesktop.systemd1",
280 "/org/freedesktop/systemd1",
281 "org.freedesktop.systemd1.Manager",
283 -1, "(o)", "(ss)", unit.c_str(), "replace").get("(o)", &job);
285 INFO(SINK, "Waiting for job: " + std::string(job));
286 if (!watch.waitForJob(job))
287 ERROR(SINK, "Starting unit: " + unit + " failed");
290 unsigned int getOptions()
292 unsigned int result = 0;
296 ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
298 result |= InternalEncryption::Option::IncludeUnusedRegion;
304 void setOptions(unsigned int options)
308 if (options & InternalEncryption::Option::IncludeUnusedRegion) {
313 ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
316 void killProcesses(std::vector<const char*> &args)
318 int pipeFd[2] = {0, };
321 if (::pipe(pipeFd) < 0)
322 throw runtime::Exception("Failed to create pipe");
328 throw runtime::Exception("Failed to fork");
333 if (::dup2(pipeFd[1], STDOUT_FILENO) < 0)
334 ERROR(SINK, "Failed to copy STDOUT_FILENO");
336 if (::dup2(STDOUT_FILENO, STDERR_FILENO) < 0)
337 ERROR(SINK, "Failed to copy STDERR_FILENO");
341 if (::execv(args[0], const_cast<char* const*>(args.data())) < 0)
342 ERROR(SINK, "Failed to execute : " + std::to_string(errno));
344 std::quick_exit(EXIT_FAILURE);
349 for (int status = 0; ::waitpid(pid, &status, 0) == -1;) {
350 if (errno != EINTR) {
352 throw runtime::Exception("Failed to wait child process");
356 auto closeFile = [](FILE *fp) { ::fclose(fp); };
357 std::unique_ptr<FILE, decltype(closeFile)> fp(::fdopen(pipeFd[0], "r"), closeFile);
360 throw runtime::Exception("Failed to open pipe descriptor");
363 char *line = nullptr;
366 while ((::getline(&line, &len, fp.get())) != -1) {
367 std::string log(line);
368 log.erase(std::find_if(log.rbegin(), log.rend(),
369 std::ptr_fun<int, int>(std::isgraph)).base(), log.end());
372 } catch (std::exception &e) {
373 ERROR(SINK, e.what());
379 bool isPartitionTerminated(const std::string &partition)
382 const std::string cmd("fuser -m " + partition + " | grep -o '[0-9]*'");
383 char *line = nullptr;
386 FILE *fp = ::popen(cmd.c_str(), "r");
388 ERROR(SINK, "Failed to get processes on partition");
392 if (::getline(&line, &len, fp) != -1)
401 void unmountInternalStorage(const std::string& source)
403 if (::umount2("/opt/usr", MNT_DETACH) == -1) {
404 if (errno != EBUSY && errno != EINVAL) {
405 throw runtime::Exception("umount() error : " + runtime::GetSystemErrorMessage());
411 std::vector<const char*> args = {
412 "/usr/bin/fuser", "-m", "-k", "-v", "-SIGTERM", source.c_str(), nullptr
416 ::usleep((useconds_t)((unsigned int)(500)*1000));
418 args[4] = "-SIGKILL";
420 ::usleep((useconds_t)((unsigned int)(200)*1000));
421 } catch (runtime::Exception &e) {
424 } while (!isPartitionTerminated(source));
429 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv,
434 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
435 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)(std::vector<unsigned char>, unsigned int));
436 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
437 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::isMounted)());
438 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::prepareEncryption)(unsigned int));
439 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::prepareDecryption)());
440 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
441 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
442 server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
443 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::recovery)());
444 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
445 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
446 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
447 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
448 server.expose(this, "", (int)(InternalEncryptionServer::getState)());
449 server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
450 server.expose(this, "", (std::string)(InternalEncryptionServer::getDevicePath)());
452 server.createNotification("InternalEncryptionServer::mount");
454 std::string source = findDevPath();
456 if (getState() == State::Encrypted) {
457 //"error_partially_encrypted"
458 if (!FileFooter::exist(source) && !UpgradeSupport::checkUpgradeFlag()) {
459 // Trigger key migration process
460 UpgradeSupport::createUpgradeFlag();
464 engine.reset(new INTERNAL_ENGINE(
465 source, INTERNAL_PATH,
466 ProgressBar([](unsigned v) {
467 ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
468 std::to_string(v).c_str());
473 dbus::Connection &systemDBus = dbus::Connection::getSystem();
474 systemDBus.registerObject(ODE_OBJECT_PATH, manifest, nullptr, nullptr);
475 } catch (runtime::Exception &e) {
476 ERROR(SINK, e.what());
480 InternalEncryptionServer::~InternalEncryptionServer()
484 int InternalEncryptionServer::migrateMasterKey(const std::string& dev, const std::string& password)
487 BinaryData masterKey = UpgradeSupport::loadMasterKey(dev);
489 // encrypt the master key with given password
490 return keyServer.changePassword2(dev, masterKey, password);
491 } catch (const runtime::Exception&) {
492 ERROR(SINK, "Failed to load the master key stored during upgrade.");
495 return error::Unknown;
498 int InternalEncryptionServer::setMountPassword(const std::string& password)
500 const std::string& dev = engine->getSource();
502 // check if upgrade flag exists
503 if (UpgradeSupport::checkUpgradeFlag()) {
504 INFO(SINK, "Upgrade flag detected.");
506 int rc = migrateMasterKey(dev, password);
507 if (rc != error::None)
509 UpgradeSupport::removeUpgradeFlag();
512 return keyServer.get(dev, password, mountKey);
515 int InternalEncryptionServer::mount(const std::vector<unsigned char> &mk, unsigned int options)
517 if (mountKey.empty() && mk.empty()) {
518 ERROR(SINK, "You need to set master key first.");
519 return error::NoData;
522 BinaryData key = mk.empty() ? mountKey : mk;
525 if (getState() != State::Encrypted) {
526 ERROR(SINK, "Cannot mount, SD partition's state incorrect.");
527 return error::NoSuchDevice;
530 if (engine->isMounted()) {
531 ERROR(SINK, "Partition already mounted.");
535 INFO(SINK, "Mounting internal storage.");
537 engine->mount(key, getOptions());
539 server.notify("InternalEncryptionServer::mount");
541 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
542 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
543 } catch (runtime::Exception &e) {
544 ERROR(SINK, "Mount failed: " + std::string(e.what()));
545 return error::Unknown;
551 int InternalEncryptionServer::isMounted()
555 ret = engine->isMounted() ? 1 : 0;
556 } catch (runtime::Exception &e) {
557 ERROR(SINK, "Failed to access the mount flag");
558 return error::Unknown;
563 int InternalEncryptionServer::umount()
565 if (getState() != State::Encrypted) {
566 ERROR(SINK, "Cannot umount, partition's state incorrect.");
567 return error::NoSuchDevice;
570 if (!engine->isMounted()) {
571 ERROR(SINK, "Partition already umounted.");
575 INFO(SINK, "Closing all processes using internal storage.");
578 INFO(SINK, "Umounting internal storage.");
579 unmountInternalStorage("/dev/mapper/userdata");
581 } catch (runtime::Exception &e) {
582 ERROR(SINK, "Umount failed: " + std::string(e.what()));
583 return error::Unknown;
589 int InternalEncryptionServer::prepareEncryption(unsigned int options)
591 if (getState() != State::Unencrypted) {
592 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
593 return error::NoSuchDevice;
597 runtime::File file("/opt/etc/.odeprogress");
598 file.create(MODE_0640);
599 } catch (runtime::Exception &e) {
600 ERROR(SINK, "Failed to create the flag file: " + std::string(e.what()));
601 return error::Unknown;
604 setOptions(options & getSupportedOptions());
606 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "prepared_encryption");
608 ::reboot(RB_AUTOBOOT);
613 int InternalEncryptionServer::prepareDecryption()
615 if (getState() != State::Encrypted) {
616 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
617 return error::NoSuchDevice;
621 runtime::File file("/opt/etc/.odeprogress");
622 file.create(MODE_0640);
623 } catch (runtime::Exception &e) {
624 ERROR(SINK, "Failed to create the flag file: " + std::string(e.what()));
625 return error::Unknown;
628 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "prepared_decryption");
630 ::reboot(RB_AUTOBOOT);
635 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
637 if (getState() != State::Unencrypted) {
638 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
639 return error::NoSuchDevice;
642 BinaryData masterKey;
643 int ret = keyServer.get(engine->getSource(), password, masterKey);
644 if (ret != error::None)
647 auto encryptWorker = [masterKey, options, this]() {
649 if (::device_power_request_lock(POWER_LOCK_DISPLAY, 0) != 0)
650 ERROR(SINK, "Failed to request to lock display");
652 showProgressUI("encrypt");
655 runtime::File file("/opt/etc/.odeprogress");
656 file.create(MODE_0640);
658 std::string source = engine->getSource();
659 auto mntPaths = findMountPointsByDevice(source);
661 if (!mntPaths.empty()) {
662 INFO(SINK, "Closing all processes using internal storage.");
665 INFO(SINK, "Unmounting internal storage.");
666 unmountInternalStorage(source);
669 INFO(SINK, "Encryption started.");
670 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
672 engine->encrypt(masterKey, options);
673 } catch (runtime::Exception &e) {
674 ERROR(SINK, e.what());
675 if (!engine->isStarted()) {
676 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
680 ::reboot(RB_AUTOBOOT);
682 setOptions(options & getSupportedOptions());
684 INFO(SINK, "Encryption completed.");
685 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
686 server.notify("InternalEncryptionServer::mount");
690 INFO(SINK, "Syncing disk and rebooting.");
692 ::reboot(RB_AUTOBOOT);
693 } catch (runtime::Exception &e) {
694 ERROR(SINK, "Encryption failed: " + std::string(e.what()));
698 std::thread asyncWork(encryptWorker);
704 int InternalEncryptionServer::decrypt(const std::string& password)
706 if (getState() != State::Encrypted) {
707 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
708 return error::NoSuchDevice;
711 // check if key migration is needed
712 if (UpgradeSupport::checkUpgradeFlag()) {
713 INFO(SINK, "Upgrade flag detected.");
714 const std::string& dev = engine->getSource();
715 int rc = migrateMasterKey(dev, password);
716 if (rc == error::None)
717 UpgradeSupport::removeUpgradeFlag();
720 BinaryData masterKey;
721 int ret = keyServer.get(engine->getSource(), password, masterKey);
722 if (ret != error::None)
725 auto decryptWorker = [masterKey, this]() {
727 if (::device_power_request_lock(POWER_LOCK_DISPLAY, 0) != 0)
728 ERROR(SINK, "Failed to request to lock display");
730 showProgressUI("decrypt");
733 runtime::File file("/opt/etc/.odeprogress");
734 file.create(MODE_0640);
736 if (engine->isMounted()) {
737 INFO(SINK, "Closing all processes using internal storage.");
740 INFO(SINK, "Umounting internal storage.");
741 unmountInternalStorage("/dev/mapper/userdata");
745 INFO(SINK, "Decryption started.");
746 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
748 engine->decrypt(masterKey, getOptions());
749 } catch (runtime::Exception &e) {
750 ERROR(SINK, e.what());
751 if (!engine->isStarted()) {
752 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
756 ::reboot(RB_AUTOBOOT);
759 INFO(SINK, "Decryption complete.");
760 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
764 INFO(SINK, "Syncing disk and rebooting.");
766 ::reboot(RB_AUTOBOOT);
767 } catch (runtime::Exception &e) {
768 ERROR(SINK, "Decryption failed: " + std::string(e.what()));
772 std::thread asyncWork(decryptWorker);
778 int InternalEncryptionServer::recovery()
780 int state = getState();
782 if (state == State::Unencrypted)
783 return error::NoSuchDevice;
785 runtime::File file("/opt/.factoryreset");
786 file.create(MODE_0640);
790 dbus::Connection& systemDBus = dbus::Connection::getSystem();
791 systemDBus.methodcall("org.tizen.system.deviced",
792 "/Org/Tizen/System/DeviceD/Power",
793 "org.tizen.system.deviced.power",
795 -1, "()", "(si)", "reboot", 0);
796 } catch (runtime::Exception &e) {
797 ::reboot(RB_AUTOBOOT);
802 int InternalEncryptionServer::isPasswordInitialized()
804 return keyServer.isInitialized(engine->getSource());
807 int InternalEncryptionServer::initPassword(const std::string& password)
809 return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
812 int InternalEncryptionServer::cleanPassword(const std::string& password)
814 return keyServer.remove(engine->getSource(), password);
817 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
818 const std::string& newPassword)
820 return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
823 int InternalEncryptionServer::verifyPassword(const std::string& password)
825 return keyServer.verifyPassword(engine->getSource(), password);
828 int InternalEncryptionServer::getState()
830 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
832 throw runtime::Exception("Failed to get vconf value.");
835 std::string valueStr(value);
838 if (valueStr == "encrypted")
839 return State::Encrypted;
840 else if (valueStr == "unencrypted")
841 return State::Unencrypted;
842 else if (valueStr == "prepared_encryption")
843 return State::PreparedEncryption;
844 else if (valueStr == "prepared_decryption")
845 return State::PreparedDecryption;
846 else if (valueStr == "error_partially_encrypted" || valueStr == "error_partially_decrypted")
847 return State::Corrupted;
849 return State::NotSupported;
852 unsigned int InternalEncryptionServer::getSupportedOptions()
854 return engine->getSupportedOptions();
857 std::string InternalEncryptionServer::getDevicePath() const
859 return engine->getSource();