2 * Copyright (c) 2015-2017 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>
44 #include "progress-bar.h"
45 #include "rmi/common.h"
47 #include "ext4-tool.h"
48 #include "internal-encryption.h"
49 #include "internal-encryption-common.h"
50 #include "upgrade-support.h"
51 #include "file-footer.h"
57 const char *PRIVILEGE_PLATFORM = "http://tizen.org/privilege/internal/default/platform";
59 // watches systemd jobs
62 explicit JobWatch(dbus::Connection& systemDBus);
65 bool waitForJob(const std::string& job);
68 void jobRemoved(const dbus::Variant& parameters);
72 const std::string& job,
73 const std::string& unit,
74 const std::string& result) : id(id), job(job), unit(unit), result(result) {}
81 dbus::Connection::SubscriptionId id;
82 dbus::Connection& systemDBus;
83 std::list<Job> removedJobs;
85 std::condition_variable jobsCv;
88 JobWatch::JobWatch(dbus::Connection& systemDBus) : systemDBus(systemDBus) {
89 auto callback = [this](dbus::Variant parameters) {
90 this->jobRemoved(parameters);
93 id = systemDBus.subscribeSignal("",
94 "/org/freedesktop/systemd1",
95 "org.freedesktop.systemd1.Manager",
100 JobWatch::~JobWatch() {
101 systemDBus.unsubscribeSignal(id);
104 bool JobWatch::waitForJob(const std::string& job) {
106 std::unique_lock<std::mutex> lock(jobsMutex);
108 auto sec = std::chrono::seconds(1);
109 jobsCv.wait_for(lock, 5*sec, [this, &timeout]{
110 if (!removedJobs.empty()) {
117 ERROR(SINK, "job: " + job + ", result: time out");
121 while(!removedJobs.empty()) {
122 bool match = (removedJobs.front().job == job);
123 bool done = (removedJobs.front().result == "done");
124 removedJobs.pop_front();
131 void JobWatch::jobRemoved(const dbus::Variant& parameters)
137 parameters.get("(uoss)", &id, &job, &unit, &result);
138 INFO(SINK, "id:" + std::to_string(id) + " job:" + job + " unit:" + unit + " result:" + result);
141 std::lock_guard<std::mutex> guard(jobsMutex);
142 removedJobs.emplace_back(id, job, unit, result);
147 std::string getDecodedPath(const std::string &path, const std::string &prefix)
149 std::string ret = path;
152 pos = ret.find(prefix);
153 if (pos != std::string::npos)
154 ret = ret.substr(prefix.size(), ret.size());
157 while ((pos = ret.find("_", pos)) != std::string::npos) {
158 int a = std::stoi(std::string(1, ret.at(pos+1)), nullptr, 16);
159 int b = std::stoi(std::string(1, ret.at(pos+2)), nullptr, 16);
161 ret.replace(pos, 3, "_");
163 ret.replace(pos, 3, std::string(1, ((a << 4) | b)));
169 void stopSystemdUnits()
171 dbus::Connection& systemDBus = dbus::Connection::getSystem();
172 dbus::VariantIterator iter;
173 std::vector<std::string> preprocessUnits;
174 std::set<std::string> unitsToStop;
176 auto stopUnit = [&systemDBus](const std::string &unit) {
177 JobWatch watch(systemDBus);
178 INFO(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 INFO(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)) {
233 char *unit = nullptr;
234 systemDBus.methodcall("org.freedesktop.systemd1",
235 "/org/freedesktop/systemd1",
236 "org.freedesktop.systemd1.Manager",
238 -1, "(o)", "(u)", (unsigned int)pid)
241 auto unescapedName = getDecodedPath(unit, "/org/freedesktop/systemd1/unit/");
242 if (unescapedName.find("dbus", 0, 4) == std::string::npos)
243 unitsToStop.insert(unescapedName);
244 } catch (runtime::Exception &e) {
245 ERROR(SINK, "Killing process: " + std::to_string(pid));
246 ::kill(pid, SIGKILL);
250 for (auto unit : unitsToStop) {
255 void showProgressUI(const std::string type)
257 dbus::Connection& systemDBus = dbus::Connection::getSystem();
258 std::string unit("ode-progress-ui@"+type+".service");
260 JobWatch watch(systemDBus);
261 INFO(SINK, "Start unit: " + unit);
263 const char* job = NULL;
264 systemDBus.methodcall("org.freedesktop.systemd1",
265 "/org/freedesktop/systemd1",
266 "org.freedesktop.systemd1.Manager",
268 -1, "(o)", "(ss)", unit.c_str(), "replace").get("(o)", &job);
270 INFO(SINK, "Waiting for job: " + std::string(job));
271 if (!watch.waitForJob(job))
272 ERROR(SINK, "Starting unit: " + unit + " failed");
275 unsigned int getOptions()
277 unsigned int result = 0;
281 ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
283 result |= InternalEncryption::Option::IncludeUnusedRegion;
289 void setOptions(unsigned int options)
293 if (options & InternalEncryption::Option::IncludeUnusedRegion) {
298 ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
301 void execAndWait(const std::string &path, std::vector<std::string> &args)
303 runtime::Process proc(path, args);
304 int ret = proc.execute();
306 ERROR(SINK, path + " failed for " + args.back());
308 ret = proc.waitForFinished();
309 if (ret < 0 || !WIFEXITED(ret) || WEXITSTATUS(ret) != 0)
310 ERROR(SINK, path + " failed for " + args.back());
313 bool isPartitionTerminated(const std::string &partition)
316 const std::string cmd("fuser -m " + partition + " | grep -o '[0-9]*'");
317 char *line = nullptr;
320 FILE *fp = ::popen(cmd.c_str(), "r");
322 ERROR(SINK, "Failed to get processes on partition");
326 if (::getline(&line, &len, fp) != -1)
335 void unmountInternalStorage(const std::string& source)
337 if (::umount2("/opt/usr", MNT_DETACH) == -1) {
338 if (errno != EBUSY && errno != EINVAL) {
339 throw runtime::Exception("umount() error : " + runtime::GetSystemErrorMessage());
345 static const char *fuserPath = "/usr/bin/fuser";
346 std::vector<std::string> args = {
347 fuserPath, "-m", "-k", "-s", "-SIGTERM", source,
349 execAndWait(fuserPath, args);
350 ::usleep((useconds_t)((unsigned int)(500)*1000));
352 args[4] = "-SIGKILL";
353 execAndWait(fuserPath, args);
354 ::usleep((useconds_t)((unsigned int)(200)*1000));
355 } while (!isPartitionTerminated(source));
360 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv,
365 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
366 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)(std::vector<unsigned char>, unsigned int));
367 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
368 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::isMounted)());
369 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
370 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
371 server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
372 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::recovery)());
373 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
374 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
375 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
376 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
377 server.expose(this, "", (int)(InternalEncryptionServer::getState)());
378 server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
379 server.expose(this, "", (std::string)(InternalEncryptionServer::getDevicePath)());
381 server.createNotification("InternalEncryptionServer::mount");
383 std::string source = findDevPath();
385 if (getState() == State::Encrypted) {
386 //"error_partially_encrypted"
387 if (!FileFooter::exist(source) && !UpgradeSupport::checkUpgradeFlag()) {
388 // Trigger key migration process
389 UpgradeSupport::createUpgradeFlag();
393 engine.reset(new INTERNAL_ENGINE(
394 source, INTERNAL_PATH,
395 ProgressBar([](int v) {
396 ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
397 std::to_string(v).c_str());
402 InternalEncryptionServer::~InternalEncryptionServer()
406 int InternalEncryptionServer::migrateMasterKey(const std::string& dev, const std::string& password)
409 BinaryData masterKey = UpgradeSupport::loadMasterKey(dev);
411 // encrypt the master key with given password
412 return keyServer.changePassword2(dev, masterKey, password);
413 } catch (const runtime::Exception&) {
414 ERROR(SINK, "Failed to load the master key stored during upgrade.");
417 return error::Unknown;
420 int InternalEncryptionServer::setMountPassword(const std::string& password)
422 const std::string& dev = engine->getSource();
424 // check if upgrade flag exists
425 if (UpgradeSupport::checkUpgradeFlag()) {
426 INFO(SINK, "Upgrade flag detected.");
428 int rc = migrateMasterKey(dev, password);
429 if (rc != error::None)
431 UpgradeSupport::removeUpgradeFlag();
434 return keyServer.get(dev, password, mountKey);
437 int InternalEncryptionServer::mount(const std::vector<unsigned char> &mk, unsigned int options)
439 if (mountKey.empty() && mk.empty()) {
440 ERROR(SINK, "You need to set master key first.");
441 return error::NoData;
444 BinaryData key = mk.empty() ? mountKey : mk;
447 if (getState() != State::Encrypted) {
448 ERROR(SINK, "Cannot mount, SD partition's state incorrect.");
449 return error::NoSuchDevice;
452 if (engine->isMounted()) {
453 ERROR(SINK, "Partition already mounted.");
457 INFO(SINK, "Mounting internal storage.");
459 engine->mount(key, getOptions());
461 server.notify("InternalEncryptionServer::mount");
463 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
464 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
465 } catch (runtime::Exception &e) {
466 ERROR(SINK, "Mount failed: " + std::string(e.what()));
467 return error::Unknown;
473 int InternalEncryptionServer::isMounted()
477 ret = engine->isMounted() ? 1 : 0;
478 } catch (runtime::Exception &e) {
479 ERROR(SINK, "Failed to access the mount flag");
480 return error::Unknown;
485 int InternalEncryptionServer::umount()
487 if (getState() != State::Encrypted) {
488 ERROR(SINK, "Cannot umount, partition's state incorrect.");
489 return error::NoSuchDevice;
492 if (!engine->isMounted()) {
493 ERROR(SINK, "Partition already umounted.");
497 INFO(SINK, "Closing all processes using internal storage.");
500 INFO(SINK, "Umounting internal storage.");
501 unmountInternalStorage("/dev/mapper/userdata");
503 } catch (runtime::Exception &e) {
504 ERROR(SINK, "Umount failed: " + std::string(e.what()));
505 return error::Unknown;
511 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
513 if (getState() != State::Unencrypted) {
514 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
515 return error::NoSuchDevice;
518 BinaryData masterKey;
519 int ret = keyServer.get(engine->getSource(), password, masterKey);
520 if (ret != error::None)
523 auto encryptWorker = [masterKey, options, this]() {
525 if (::device_power_request_lock(POWER_LOCK_DISPLAY, 0) != 0)
526 ERROR(SINK, "Failed to request to lock display");
528 showProgressUI("encrypt");
531 runtime::File file("/opt/etc/.odeprogress");
534 std::string source = engine->getSource();
535 auto mntPaths = findMountPointsByDevice(source);
537 if (!mntPaths.empty()) {
538 INFO(SINK, "Closing all processes using internal storage.");
541 INFO(SINK, "Unmounting internal storage.");
542 unmountInternalStorage(source);
545 INFO(SINK, "Encryption started.");
546 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
548 engine->encrypt(masterKey, options);
549 } catch (runtime::Exception &e) {
550 ERROR(SINK, e.what());
551 if (!engine->isStarted()) {
552 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
556 ::reboot(RB_AUTOBOOT);
558 setOptions(options & getSupportedOptions());
560 INFO(SINK, "Encryption completed.");
561 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
562 server.notify("InternalEncryptionServer::mount");
566 INFO(SINK, "Syncing disk and rebooting.");
568 ::reboot(RB_AUTOBOOT);
569 } catch (runtime::Exception &e) {
570 ERROR(SINK, "Encryption failed: " + std::string(e.what()));
574 std::thread asyncWork(encryptWorker);
580 int InternalEncryptionServer::decrypt(const std::string& password)
582 if (getState() != State::Encrypted) {
583 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
584 return error::NoSuchDevice;
587 // check if key migration is needed
588 if (UpgradeSupport::checkUpgradeFlag()) {
589 INFO(SINK, "Upgrade flag detected.");
590 const std::string& dev = engine->getSource();
591 int rc = migrateMasterKey(dev, password);
592 if (rc == error::None)
593 UpgradeSupport::removeUpgradeFlag();
596 BinaryData masterKey;
597 int ret = keyServer.get(engine->getSource(), password, masterKey);
598 if (ret != error::None)
601 auto decryptWorker = [masterKey, this]() {
603 if (::device_power_request_lock(POWER_LOCK_DISPLAY, 0) != 0)
604 ERROR(SINK, "Failed to request to lock display");
606 showProgressUI("decrypt");
609 runtime::File file("/opt/etc/.odeprogress");
612 if (engine->isMounted()) {
613 INFO(SINK, "Closing all processes using internal storage.");
616 INFO(SINK, "Umounting internal storage.");
617 unmountInternalStorage("/dev/mapper/userdata");
621 INFO(SINK, "Decryption started.");
622 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
624 engine->decrypt(masterKey, getOptions());
625 } catch (runtime::Exception &e) {
626 ERROR(SINK, e.what());
627 if (!engine->isStarted()) {
628 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
632 ::reboot(RB_AUTOBOOT);
635 INFO(SINK, "Decryption complete.");
636 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
640 INFO(SINK, "Syncing disk and rebooting.");
642 ::reboot(RB_AUTOBOOT);
643 } catch (runtime::Exception &e) {
644 ERROR(SINK, "Decryption failed: " + std::string(e.what()));
648 std::thread asyncWork(decryptWorker);
654 int InternalEncryptionServer::recovery()
656 int state = getState();
658 if (state == State::Unencrypted)
659 return error::NoSuchDevice;
661 runtime::File file("/opt/.factoryreset");
666 dbus::Connection& systemDBus = dbus::Connection::getSystem();
667 systemDBus.methodcall("org.tizen.system.deviced",
668 "/Org/Tizen/System/DeviceD/Power",
669 "org.tizen.system.deviced.power",
671 -1, "()", "(si)", "reboot", 0);
672 } catch (runtime::Exception &e) {
673 ::reboot(RB_AUTOBOOT);
678 int InternalEncryptionServer::isPasswordInitialized()
680 return keyServer.isInitialized(engine->getSource());
683 int InternalEncryptionServer::initPassword(const std::string& password)
685 return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
688 int InternalEncryptionServer::cleanPassword(const std::string& password)
690 return keyServer.remove(engine->getSource(), password);
693 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
694 const std::string& newPassword)
696 return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
699 int InternalEncryptionServer::verifyPassword(const std::string& password)
701 return keyServer.verifyPassword(engine->getSource(), password);
704 int InternalEncryptionServer::getState()
706 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
708 throw runtime::Exception("Failed to get vconf value.");
711 std::string valueStr(value);
714 if (valueStr == "encrypted")
715 return State::Encrypted;
716 else if (valueStr == "unencrypted")
717 return State::Unencrypted;
718 else if (valueStr == "error_partially_encrypted" || valueStr == "error_partially_decrypted")
719 return State::Corrupted;
721 return State::NotSupported;
724 unsigned int InternalEncryptionServer::getSupportedOptions()
726 return engine->getSupportedOptions();
729 std::string InternalEncryptionServer::getDevicePath() const
731 return engine->getSource();