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)) {
212 char *unit = nullptr;
213 systemDBus.methodcall("org.freedesktop.systemd1",
214 "/org/freedesktop/systemd1",
215 "org.freedesktop.systemd1.Manager",
217 -1, "(o)", "(u)", (unsigned int)pid)
221 int err = sd_bus_path_decode(unit, "/org/freedesktop/systemd1/unit", &tmp);
222 if (err <= 0 || tmp == NULL) {
223 ERROR(SINK, "Failed to decode unit name: " + std::string(unit) + " error: " +
224 std::to_string(err));
227 std::string unescapedName(tmp);
230 if (unescapedName.find("dbus", 0, 4) == std::string::npos)
231 unitsToStop.insert(unescapedName);
232 } catch (runtime::Exception &e) {
233 ERROR(SINK, "Killing process: " + std::to_string(pid));
234 ::kill(pid, SIGKILL);
238 for (auto unit : unitsToStop) {
243 void showProgressUI(const std::string type)
245 dbus::Connection& systemDBus = dbus::Connection::getSystem();
246 std::string unit("ode-progress-ui@"+type+".service");
248 JobWatch watch(systemDBus);
249 INFO(SINK, "Start unit: " + unit);
251 const char* job = NULL;
252 systemDBus.methodcall("org.freedesktop.systemd1",
253 "/org/freedesktop/systemd1",
254 "org.freedesktop.systemd1.Manager",
256 -1, "(o)", "(ss)", unit.c_str(), "replace").get("(o)", &job);
258 INFO(SINK, "Waiting for job: " + std::string(job));
259 if (!watch.waitForJob(job))
260 ERROR(SINK, "Starting unit: " + unit + " failed");
263 unsigned int getOptions()
265 unsigned int result = 0;
269 ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
271 result |= InternalEncryption::Option::IncludeUnusedRegion;
277 void setOptions(unsigned int options)
281 if (options & InternalEncryption::Option::IncludeUnusedRegion) {
286 ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
289 void execAndWait(const std::string &path, std::vector<std::string> &args)
291 runtime::Process proc(path, args);
292 int ret = proc.execute();
294 ERROR(SINK, "Executing " + path + " failed for " + args.back());
296 ret = proc.waitForFinished();
297 if (ret < 0 || !WIFEXITED(ret) || WEXITSTATUS(ret) != 0)
298 ERROR(SINK, "Waiting for " + path + " failed for " + args.back());
301 bool isPartitionTerminated(const std::string &partition)
304 const std::string cmd("fuser -m " + partition + " | grep -o '[0-9]*'");
305 char *line = nullptr;
308 FILE *fp = ::popen(cmd.c_str(), "r");
310 ERROR(SINK, "Failed to get processes on partition");
314 if (::getline(&line, &len, fp) != -1)
323 void unmountInternalStorage(const std::string& source)
325 if (::umount2("/opt/usr", MNT_DETACH) == -1) {
326 if (errno != EBUSY && errno != EINVAL) {
327 throw runtime::Exception("umount() error : " + runtime::GetSystemErrorMessage());
333 static const char *fuserPath = "/usr/bin/fuser";
334 std::vector<std::string> args = {
335 fuserPath, "-m", "-k", "-s", "-SIGTERM", source,
337 execAndWait(fuserPath, args);
338 ::usleep((useconds_t)((unsigned int)(500)*1000));
340 args[4] = "-SIGKILL";
341 execAndWait(fuserPath, args);
342 ::usleep((useconds_t)((unsigned int)(200)*1000));
343 } while (!isPartitionTerminated(source));
348 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv,
353 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
354 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)(std::vector<unsigned char>, unsigned int));
355 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
356 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::isMounted)());
357 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
358 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
359 server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
360 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::recovery)());
361 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
362 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
363 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
364 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
365 server.expose(this, "", (int)(InternalEncryptionServer::getState)());
366 server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
367 server.expose(this, "", (std::string)(InternalEncryptionServer::getDevicePath)());
369 server.createNotification("InternalEncryptionServer::mount");
371 std::string source = findDevPath();
373 if (getState() == State::Encrypted) {
374 //"error_partially_encrypted"
375 if (!FileFooter::exist(source) && !UpgradeSupport::checkUpgradeFlag()) {
376 // Trigger key migration process
377 UpgradeSupport::createUpgradeFlag();
381 engine.reset(new INTERNAL_ENGINE(
382 source, INTERNAL_PATH,
383 ProgressBar([](int v) {
384 ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
385 std::to_string(v).c_str());
390 InternalEncryptionServer::~InternalEncryptionServer()
394 int InternalEncryptionServer::migrateMasterKey(const std::string& dev, const std::string& password)
397 BinaryData masterKey = UpgradeSupport::loadMasterKey(dev);
399 // encrypt the master key with given password
400 return keyServer.changePassword2(dev, masterKey, password);
401 } catch (const runtime::Exception&) {
402 ERROR(SINK, "Failed to load the master key stored during upgrade.");
405 return error::Unknown;
408 int InternalEncryptionServer::setMountPassword(const std::string& password)
410 const std::string& dev = engine->getSource();
412 // check if upgrade flag exists
413 if (UpgradeSupport::checkUpgradeFlag()) {
414 INFO(SINK, "Upgrade flag detected.");
416 int rc = migrateMasterKey(dev, password);
417 if (rc != error::None)
419 UpgradeSupport::removeUpgradeFlag();
422 return keyServer.get(dev, password, mountKey);
425 int InternalEncryptionServer::mount(const std::vector<unsigned char> &mk, unsigned int options)
427 if (mountKey.empty() && mk.empty()) {
428 ERROR(SINK, "You need to set master key first.");
429 return error::NoData;
432 BinaryData key = mk.empty() ? mountKey : mk;
435 if (getState() != State::Encrypted) {
436 ERROR(SINK, "Cannot mount, SD partition's state incorrect.");
437 return error::NoSuchDevice;
440 if (engine->isMounted()) {
441 ERROR(SINK, "Partition already mounted.");
445 INFO(SINK, "Mounting internal storage.");
447 engine->mount(key, getOptions());
449 server.notify("InternalEncryptionServer::mount");
451 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
452 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
453 } catch (runtime::Exception &e) {
454 ERROR(SINK, "Mount failed: " + std::string(e.what()));
455 return error::Unknown;
461 int InternalEncryptionServer::isMounted()
465 ret = engine->isMounted() ? 1 : 0;
466 } catch (runtime::Exception &e) {
467 ERROR(SINK, "Failed to access the mount flag");
468 return error::Unknown;
473 int InternalEncryptionServer::umount()
475 if (getState() != State::Encrypted) {
476 ERROR(SINK, "Cannot umount, partition's state incorrect.");
477 return error::NoSuchDevice;
480 if (!engine->isMounted()) {
481 ERROR(SINK, "Partition already umounted.");
485 INFO(SINK, "Closing all processes using internal storage.");
488 INFO(SINK, "Umounting internal storage.");
489 unmountInternalStorage("/dev/mapper/userdata");
491 } catch (runtime::Exception &e) {
492 ERROR(SINK, "Umount failed: " + std::string(e.what()));
493 return error::Unknown;
499 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
501 if (getState() != State::Unencrypted) {
502 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
503 return error::NoSuchDevice;
506 BinaryData masterKey;
507 int ret = keyServer.get(engine->getSource(), password, masterKey);
508 if (ret != error::None)
511 auto encryptWorker = [masterKey, options, this]() {
513 if (::device_power_request_lock(POWER_LOCK_DISPLAY, 0) != 0)
514 ERROR(SINK, "Failed to request to lock display");
516 showProgressUI("encrypt");
519 runtime::File file("/opt/etc/.odeprogress");
522 std::string source = engine->getSource();
523 auto mntPaths = findMountPointsByDevice(source);
525 if (!mntPaths.empty()) {
526 INFO(SINK, "Closing all processes using internal storage.");
529 INFO(SINK, "Unmounting internal storage.");
530 unmountInternalStorage(source);
533 INFO(SINK, "Encryption started.");
534 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
536 engine->encrypt(masterKey, options);
537 } catch (runtime::Exception &e) {
538 ERROR(SINK, e.what());
539 if (!engine->isStarted()) {
540 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
544 ::reboot(RB_AUTOBOOT);
546 setOptions(options & getSupportedOptions());
548 INFO(SINK, "Encryption completed.");
549 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
550 server.notify("InternalEncryptionServer::mount");
554 INFO(SINK, "Syncing disk and rebooting.");
556 ::reboot(RB_AUTOBOOT);
557 } catch (runtime::Exception &e) {
558 ERROR(SINK, "Encryption failed: " + std::string(e.what()));
562 std::thread asyncWork(encryptWorker);
568 int InternalEncryptionServer::decrypt(const std::string& password)
570 if (getState() != State::Encrypted) {
571 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
572 return error::NoSuchDevice;
575 // check if key migration is needed
576 if (UpgradeSupport::checkUpgradeFlag()) {
577 INFO(SINK, "Upgrade flag detected.");
578 const std::string& dev = engine->getSource();
579 int rc = migrateMasterKey(dev, password);
580 if (rc == error::None)
581 UpgradeSupport::removeUpgradeFlag();
584 BinaryData masterKey;
585 int ret = keyServer.get(engine->getSource(), password, masterKey);
586 if (ret != error::None)
589 auto decryptWorker = [masterKey, this]() {
591 if (::device_power_request_lock(POWER_LOCK_DISPLAY, 0) != 0)
592 ERROR(SINK, "Failed to request to lock display");
594 showProgressUI("decrypt");
597 runtime::File file("/opt/etc/.odeprogress");
600 if (engine->isMounted()) {
601 INFO(SINK, "Closing all processes using internal storage.");
604 INFO(SINK, "Umounting internal storage.");
605 unmountInternalStorage("/dev/mapper/userdata");
609 INFO(SINK, "Decryption started.");
610 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
612 engine->decrypt(masterKey, getOptions());
613 } catch (runtime::Exception &e) {
614 ERROR(SINK, e.what());
615 if (!engine->isStarted()) {
616 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
620 ::reboot(RB_AUTOBOOT);
623 INFO(SINK, "Decryption complete.");
624 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
628 INFO(SINK, "Syncing disk and rebooting.");
630 ::reboot(RB_AUTOBOOT);
631 } catch (runtime::Exception &e) {
632 ERROR(SINK, "Decryption failed: " + std::string(e.what()));
636 std::thread asyncWork(decryptWorker);
642 int InternalEncryptionServer::recovery()
644 int state = getState();
646 if (state == State::Unencrypted)
647 return error::NoSuchDevice;
649 runtime::File file("/opt/.factoryreset");
654 dbus::Connection& systemDBus = dbus::Connection::getSystem();
655 systemDBus.methodcall("org.tizen.system.deviced",
656 "/Org/Tizen/System/DeviceD/Power",
657 "org.tizen.system.deviced.power",
659 -1, "()", "(si)", "reboot", 0);
660 } catch (runtime::Exception &e) {
661 ::reboot(RB_AUTOBOOT);
666 int InternalEncryptionServer::isPasswordInitialized()
668 return keyServer.isInitialized(engine->getSource());
671 int InternalEncryptionServer::initPassword(const std::string& password)
673 return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
676 int InternalEncryptionServer::cleanPassword(const std::string& password)
678 return keyServer.remove(engine->getSource(), password);
681 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
682 const std::string& newPassword)
684 return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
687 int InternalEncryptionServer::verifyPassword(const std::string& password)
689 return keyServer.verifyPassword(engine->getSource(), password);
692 int InternalEncryptionServer::getState()
694 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
696 throw runtime::Exception("Failed to get vconf value.");
699 std::string valueStr(value);
702 if (valueStr == "encrypted")
703 return State::Encrypted;
704 else if (valueStr == "unencrypted")
705 return State::Unencrypted;
706 else if (valueStr == "error_partially_encrypted" || valueStr == "error_partially_decrypted")
707 return State::Corrupted;
709 return State::NotSupported;
712 unsigned int InternalEncryptionServer::getSupportedOptions()
714 return engine->getSupportedOptions();
717 std::string InternalEncryptionServer::getDevicePath() const
719 return engine->getSource();