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>
34 #include <tzplatform_config.h>
35 #include <device/power.h>
36 #include <klay/process.h>
37 #include <klay/file-user.h>
38 #include <klay/filesystem.h>
39 #include <klay/dbus/connection.h>
40 #include <klay/error.h>
41 #include <systemd/sd-bus.h>
45 #include "progress-bar.h"
46 #include "rmi/common.h"
48 #include "ext4-tool.h"
49 #include "internal-encryption.h"
50 #include "internal-encryption-common.h"
51 #include "upgrade-support.h"
52 #include "file-footer.h"
58 const char *PRIVILEGE_PLATFORM = "http://tizen.org/privilege/internal/default/platform";
60 // watches systemd jobs
63 explicit JobWatch(dbus::Connection& systemDBus);
66 bool waitForJob(const std::string& job);
69 void jobRemoved(const dbus::Variant& parameters);
73 const std::string& job,
74 const std::string& unit,
75 const std::string& result) : id(id), job(job), unit(unit), result(result) {}
82 dbus::Connection::SubscriptionId id;
83 dbus::Connection& systemDBus;
84 std::list<Job> removedJobs;
86 std::condition_variable jobsCv;
89 JobWatch::JobWatch(dbus::Connection& systemDBus) : systemDBus(systemDBus) {
90 auto callback = [this](dbus::Variant parameters) {
91 this->jobRemoved(parameters);
94 id = systemDBus.subscribeSignal("",
95 "/org/freedesktop/systemd1",
96 "org.freedesktop.systemd1.Manager",
101 JobWatch::~JobWatch() {
102 systemDBus.unsubscribeSignal(id);
105 bool JobWatch::waitForJob(const std::string& job) {
107 std::unique_lock<std::mutex> lock(jobsMutex);
109 auto sec = std::chrono::seconds(1);
110 jobsCv.wait_for(lock, 5*sec, [this, &timeout]{
111 if (!removedJobs.empty()) {
118 ERROR(SINK, "job: " + job + ", result: time out");
122 while(!removedJobs.empty()) {
123 bool match = (removedJobs.front().job == job);
124 bool done = (removedJobs.front().result == "done");
125 removedJobs.pop_front();
132 void JobWatch::jobRemoved(const dbus::Variant& parameters)
138 parameters.get("(uoss)", &id, &job, &unit, &result);
139 WARN(SINK, "id:" + std::to_string(id) + " job:" + job + " unit:" + unit + " result:" + result);
142 std::lock_guard<std::mutex> guard(jobsMutex);
143 removedJobs.emplace_back(id, job, unit, result);
148 void stopSystemdUnits()
150 dbus::Connection& systemDBus = dbus::Connection::getSystem();
151 dbus::VariantIterator iter;
152 std::vector<std::string> preprocessUnits;
153 std::set<std::string> unitsToStop;
155 auto stopUnit = [&systemDBus](const std::string &unit) {
156 JobWatch watch(systemDBus);
157 WARN(SINK, "Stopping unit: " + unit);
158 const char* job = NULL;
160 systemDBus.methodcall("org.freedesktop.systemd1",
161 "/org/freedesktop/systemd1",
162 "org.freedesktop.systemd1.Manager",
164 -1, "(o)", "(ss)", unit.c_str(), "flush").get("(o)", &job);
165 WARN(SINK, "Waiting for job: " + std::string(job));
166 if (!watch.waitForJob(job))
167 ERROR(SINK, "Stopping unit: " + unit + " failed");
168 } catch (runtime::Exception &e) {
169 ERROR(SINK, std::string(e.what()));
174 systemDBus.methodcall("org.freedesktop.systemd1",
175 "/org/freedesktop/systemd1",
176 "org.freedesktop.systemd1.Manager",
178 -1, "(a(ssssssouso))", "").get("(a(ssssssouso))", &iter);
179 } catch (runtime::Exception &e) {
180 ERROR(SINK, "Get list of systemd unit : " + std::string(e.what()));
184 unsigned int dataUnit;
187 ret = iter.get("(ssssssouso)", dataStr, dataStr + 1, dataStr + 2,
188 dataStr + 3, dataStr + 4, dataStr + 5,
189 dataStr + 6, &dataUnit, dataStr + 7, dataStr + 8);
193 std::string unitName(dataStr[0]);
194 if (unitName == "security-manager.socket" ||
195 unitName == "connman.socket" ||
196 unitName == "msg-server.socket") {
197 preprocessUnits.insert(preprocessUnits.begin(), unitName);
198 } else if (unitName.compare(0, 5, "user@") == 0 ||
199 unitName == "tlm.service" ||
200 unitName == "resourced.service" ||
201 unitName == "security-manager.service") {
202 preprocessUnits.push_back(unitName);
206 for (auto unit : preprocessUnits) {
210 for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
211 auto pgid = ::getpgid(pid);
212 if (pgid > 0 && pid != pgid) {
213 WARN(SINK, "PGID doesn't match - pgid : " + std::to_string(pgid) + ", pid : " + std::to_string(pid));
218 char *unit = nullptr;
219 systemDBus.methodcall("org.freedesktop.systemd1",
220 "/org/freedesktop/systemd1",
221 "org.freedesktop.systemd1.Manager",
223 -1, "(o)", "(u)", (unsigned int)pid)
227 int err = sd_bus_path_decode(unit, "/org/freedesktop/systemd1/unit", &tmp);
228 if (err <= 0 || tmp == NULL) {
229 ERROR(SINK, "Failed to decode unit name: " + std::string(unit) + " error: " +
230 std::to_string(err));
233 std::string unescapedName(tmp);
236 unitsToStop.insert(unescapedName);
237 } catch (runtime::Exception &e) {
238 ERROR(SINK, "Killing process: " + std::to_string(pid));
239 ::kill(pid, SIGKILL);
243 for (auto unit : unitsToStop) {
248 void showProgressUI(const std::string type)
250 dbus::Connection& systemDBus = dbus::Connection::getSystem();
251 std::string unit("ode-progress-ui@"+type+".service");
253 JobWatch watch(systemDBus);
254 INFO(SINK, "Start unit: " + unit);
256 const char* job = NULL;
257 systemDBus.methodcall("org.freedesktop.systemd1",
258 "/org/freedesktop/systemd1",
259 "org.freedesktop.systemd1.Manager",
261 -1, "(o)", "(ss)", unit.c_str(), "replace").get("(o)", &job);
263 INFO(SINK, "Waiting for job: " + std::string(job));
264 if (!watch.waitForJob(job))
265 ERROR(SINK, "Starting unit: " + unit + " failed");
268 unsigned int getOptions()
270 unsigned int result = 0;
274 ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
276 result |= InternalEncryption::Option::IncludeUnusedRegion;
282 void setOptions(unsigned int options)
286 if (options & InternalEncryption::Option::IncludeUnusedRegion) {
291 ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
294 void execAndWait(const std::string &path, std::vector<std::string> &args)
296 runtime::Process proc(path, args);
297 int ret = proc.execute();
299 ERROR(SINK, "Executing " + path + " failed for " + args.back());
301 ret = proc.waitForFinished();
302 if (ret < 0 || !WIFEXITED(ret) || WEXITSTATUS(ret) != 0)
303 ERROR(SINK, "Waiting for " + path + " failed for " + args.back());
306 bool isPartitionTerminated(const std::string &partition)
309 const std::string cmd("fuser -m " + partition + " | grep -o '[0-9]*'");
310 char *line = nullptr;
313 FILE *fp = ::popen(cmd.c_str(), "r");
315 ERROR(SINK, "Failed to get processes on partition");
319 if (::getline(&line, &len, fp) != -1)
328 void unmountInternalStorage(const std::string& source)
330 if (::umount2("/opt/usr", MNT_DETACH) == -1) {
331 if (errno != EBUSY && errno != EINVAL) {
332 throw runtime::Exception("umount() error : " + runtime::GetSystemErrorMessage());
338 static const char *fuserPath = "/usr/bin/fuser";
339 std::vector<std::string> args = {
340 fuserPath, "-m", "-k", "-s", "-SIGTERM", source,
342 execAndWait(fuserPath, args);
343 ::usleep((useconds_t)((unsigned int)(500)*1000));
345 args[4] = "-SIGKILL";
346 execAndWait(fuserPath, args);
347 ::usleep((useconds_t)((unsigned int)(200)*1000));
348 } while (!isPartitionTerminated(source));
353 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv,
358 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
359 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)(std::vector<unsigned char>, unsigned int));
360 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
361 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::isMounted)());
362 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
363 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
364 server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
365 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::recovery)());
366 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
367 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
368 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
369 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
370 server.expose(this, "", (int)(InternalEncryptionServer::getState)());
371 server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
372 server.expose(this, "", (std::string)(InternalEncryptionServer::getDevicePath)());
374 server.createNotification("InternalEncryptionServer::mount");
376 std::string source = findDevPath();
378 if (getState() == State::Encrypted) {
379 //"error_partially_encrypted"
380 if (!FileFooter::exist(source) && !UpgradeSupport::checkUpgradeFlag()) {
381 // Trigger key migration process
382 UpgradeSupport::createUpgradeFlag();
386 engine.reset(new INTERNAL_ENGINE(
387 source, INTERNAL_PATH,
388 ProgressBar([](int v) {
389 ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
390 std::to_string(v).c_str());
395 InternalEncryptionServer::~InternalEncryptionServer()
399 int InternalEncryptionServer::migrateMasterKey(const std::string& dev, const std::string& password)
402 BinaryData masterKey = UpgradeSupport::loadMasterKey(dev);
404 // encrypt the master key with given password
405 return keyServer.changePassword2(dev, masterKey, password);
406 } catch (const runtime::Exception&) {
407 ERROR(SINK, "Failed to load the master key stored during upgrade.");
410 return error::Unknown;
413 int InternalEncryptionServer::setMountPassword(const std::string& password)
415 const std::string& dev = engine->getSource();
417 // check if upgrade flag exists
418 if (UpgradeSupport::checkUpgradeFlag()) {
419 INFO(SINK, "Upgrade flag detected.");
421 int rc = migrateMasterKey(dev, password);
422 if (rc != error::None)
424 UpgradeSupport::removeUpgradeFlag();
427 return keyServer.get(dev, password, mountKey);
430 int InternalEncryptionServer::mount(const std::vector<unsigned char> &mk, unsigned int options)
432 if (mountKey.empty() && mk.empty()) {
433 ERROR(SINK, "You need to set master key first.");
434 return error::NoData;
437 BinaryData key = mk.empty() ? mountKey : mk;
440 if (getState() != State::Encrypted) {
441 ERROR(SINK, "Cannot mount, SD partition's state incorrect.");
442 return error::NoSuchDevice;
445 if (engine->isMounted()) {
446 ERROR(SINK, "Partition already mounted.");
450 INFO(SINK, "Mounting internal storage.");
452 engine->mount(key, getOptions());
454 server.notify("InternalEncryptionServer::mount");
456 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
457 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
458 } catch (runtime::Exception &e) {
459 ERROR(SINK, "Mount failed: " + std::string(e.what()));
460 return error::Unknown;
466 int InternalEncryptionServer::isMounted()
470 ret = engine->isMounted() ? 1 : 0;
471 } catch (runtime::Exception &e) {
472 ERROR(SINK, "Failed to access the mount flag");
473 return error::Unknown;
478 int InternalEncryptionServer::umount()
480 if (getState() != State::Encrypted) {
481 ERROR(SINK, "Cannot umount, partition's state incorrect.");
482 return error::NoSuchDevice;
485 if (!engine->isMounted()) {
486 ERROR(SINK, "Partition already umounted.");
490 INFO(SINK, "Closing all processes using internal storage.");
493 INFO(SINK, "Umounting internal storage.");
494 unmountInternalStorage("/dev/mapper/userdata");
496 } catch (runtime::Exception &e) {
497 ERROR(SINK, "Umount failed: " + std::string(e.what()));
498 return error::Unknown;
504 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
506 if (getState() != State::Unencrypted) {
507 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
508 return error::NoSuchDevice;
511 BinaryData masterKey;
512 int ret = keyServer.get(engine->getSource(), password, masterKey);
513 if (ret != error::None)
516 auto encryptWorker = [masterKey, options, this]() {
518 if (::device_power_request_lock(POWER_LOCK_DISPLAY, 0) != 0)
519 ERROR(SINK, "Failed to request to lock display");
521 showProgressUI("encrypt");
524 runtime::File file("/opt/etc/.odeprogress");
527 std::string source = engine->getSource();
528 auto mntPaths = findMountPointsByDevice(source);
530 if (!mntPaths.empty()) {
531 INFO(SINK, "Closing all processes using internal storage.");
534 INFO(SINK, "Unmounting internal storage.");
535 unmountInternalStorage(source);
538 INFO(SINK, "Encryption started.");
539 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
541 engine->encrypt(masterKey, options);
542 } catch (runtime::Exception &e) {
543 ERROR(SINK, e.what());
544 if (!engine->isStarted()) {
545 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
549 ::reboot(RB_AUTOBOOT);
551 setOptions(options & getSupportedOptions());
553 INFO(SINK, "Encryption completed.");
554 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
555 server.notify("InternalEncryptionServer::mount");
559 INFO(SINK, "Syncing disk and rebooting.");
561 ::reboot(RB_AUTOBOOT);
562 } catch (runtime::Exception &e) {
563 ERROR(SINK, "Encryption failed: " + std::string(e.what()));
567 std::thread asyncWork(encryptWorker);
573 int InternalEncryptionServer::decrypt(const std::string& password)
575 if (getState() != State::Encrypted) {
576 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
577 return error::NoSuchDevice;
580 // check if key migration is needed
581 if (UpgradeSupport::checkUpgradeFlag()) {
582 INFO(SINK, "Upgrade flag detected.");
583 const std::string& dev = engine->getSource();
584 int rc = migrateMasterKey(dev, password);
585 if (rc == error::None)
586 UpgradeSupport::removeUpgradeFlag();
589 BinaryData masterKey;
590 int ret = keyServer.get(engine->getSource(), password, masterKey);
591 if (ret != error::None)
594 auto decryptWorker = [masterKey, this]() {
596 if (::device_power_request_lock(POWER_LOCK_DISPLAY, 0) != 0)
597 ERROR(SINK, "Failed to request to lock display");
599 showProgressUI("decrypt");
602 runtime::File file("/opt/etc/.odeprogress");
605 if (engine->isMounted()) {
606 INFO(SINK, "Closing all processes using internal storage.");
609 INFO(SINK, "Umounting internal storage.");
610 unmountInternalStorage("/dev/mapper/userdata");
614 INFO(SINK, "Decryption started.");
615 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
617 engine->decrypt(masterKey, getOptions());
618 } catch (runtime::Exception &e) {
619 ERROR(SINK, e.what());
620 if (!engine->isStarted()) {
621 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
625 ::reboot(RB_AUTOBOOT);
628 INFO(SINK, "Decryption complete.");
629 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
633 INFO(SINK, "Syncing disk and rebooting.");
635 ::reboot(RB_AUTOBOOT);
636 } catch (runtime::Exception &e) {
637 ERROR(SINK, "Decryption failed: " + std::string(e.what()));
641 std::thread asyncWork(decryptWorker);
647 int InternalEncryptionServer::recovery()
649 int state = getState();
651 if (state == State::Unencrypted)
652 return error::NoSuchDevice;
654 runtime::File file("/opt/.factoryreset");
659 dbus::Connection& systemDBus = dbus::Connection::getSystem();
660 systemDBus.methodcall("org.tizen.system.deviced",
661 "/Org/Tizen/System/DeviceD/Power",
662 "org.tizen.system.deviced.power",
664 -1, "()", "(si)", "reboot", 0);
665 } catch (runtime::Exception &e) {
666 ::reboot(RB_AUTOBOOT);
671 int InternalEncryptionServer::isPasswordInitialized()
673 return keyServer.isInitialized(engine->getSource());
676 int InternalEncryptionServer::initPassword(const std::string& password)
678 return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
681 int InternalEncryptionServer::cleanPassword(const std::string& password)
683 return keyServer.remove(engine->getSource(), password);
686 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
687 const std::string& newPassword)
689 return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
692 int InternalEncryptionServer::verifyPassword(const std::string& password)
694 return keyServer.verifyPassword(engine->getSource(), password);
697 int InternalEncryptionServer::getState()
699 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
701 throw runtime::Exception("Failed to get vconf value.");
704 std::string valueStr(value);
707 if (valueStr == "encrypted")
708 return State::Encrypted;
709 else if (valueStr == "unencrypted")
710 return State::Unencrypted;
711 else if (valueStr == "error_partially_encrypted" || valueStr == "error_partially_decrypted")
712 return State::Corrupted;
714 return State::NotSupported;
717 unsigned int InternalEncryptionServer::getSupportedOptions()
719 return engine->getSupportedOptions();
722 std::string InternalEncryptionServer::getDevicePath() const
724 return engine->getSource();