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 unitsToStop.insert(unescapedName);
243 } catch (runtime::Exception &e) {
244 ERROR(SINK, "Killing process: " + std::to_string(pid));
245 ::kill(pid, SIGKILL);
249 for (auto unit : unitsToStop) {
254 void showProgressUI(const std::string type)
256 dbus::Connection& systemDBus = dbus::Connection::getSystem();
257 std::string unit("ode-progress-ui@"+type+".service");
259 JobWatch watch(systemDBus);
260 INFO(SINK, "Start unit: " + unit);
262 const char* job = NULL;
263 systemDBus.methodcall("org.freedesktop.systemd1",
264 "/org/freedesktop/systemd1",
265 "org.freedesktop.systemd1.Manager",
267 -1, "(o)", "(ss)", unit.c_str(), "replace").get("(o)", &job);
269 INFO(SINK, "Waiting for job: " + std::string(job));
270 if (!watch.waitForJob(job))
271 ERROR(SINK, "Starting unit: " + unit + " failed");
274 unsigned int getOptions()
276 unsigned int result = 0;
280 ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
282 result |= InternalEncryption::Option::IncludeUnusedRegion;
288 void setOptions(unsigned int options)
292 if (options & InternalEncryption::Option::IncludeUnusedRegion) {
297 ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
300 void execAndWait(const std::string &path, std::vector<std::string> &args)
302 runtime::Process proc(path, args);
303 int ret = proc.execute();
305 ERROR(SINK, path + " failed for " + args.back());
307 ret = proc.waitForFinished();
308 if (ret < 0 || !WIFEXITED(ret) || WEXITSTATUS(ret) != 0)
309 ERROR(SINK, path + " failed for " + args.back());
312 bool isPartitionTerminated(const std::string &partition)
315 const std::string cmd("fuser -m " + partition + " | grep -o '[0-9]*'");
316 char *line = nullptr;
319 FILE *fp = ::popen(cmd.c_str(), "r");
321 ERROR(SINK, "Failed to get processes on partition");
325 if (::getline(&line, &len, fp) != -1)
334 void unmountInternalStorage(const std::string& source)
336 if (::umount2("/opt/usr", MNT_DETACH) == -1) {
337 if (errno != EBUSY && errno != EINVAL) {
338 throw runtime::Exception("umount() error : " + runtime::GetSystemErrorMessage());
344 static const char *fuserPath = "/usr/bin/fuser";
345 std::vector<std::string> args = {
346 fuserPath, "-m", "-k", "-s", "-SIGTERM", source,
348 execAndWait(fuserPath, args);
349 ::usleep((useconds_t)((unsigned int)(500)*1000));
351 args[4] = "-SIGKILL";
352 execAndWait(fuserPath, args);
353 ::usleep((useconds_t)((unsigned int)(200)*1000));
354 } while (!isPartitionTerminated(source));
359 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv,
364 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
365 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)(std::vector<unsigned char>, unsigned int));
366 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
367 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::isMounted)());
368 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
369 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
370 server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
371 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::recovery)());
372 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
373 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
374 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
375 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
376 server.expose(this, "", (int)(InternalEncryptionServer::getState)());
377 server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
378 server.expose(this, "", (std::string)(InternalEncryptionServer::getDevicePath)());
380 server.createNotification("InternalEncryptionServer::mount");
382 std::string source = findDevPath();
384 if (getState() == State::Encrypted) {
385 //"error_partially_encrypted"
386 if (!FileFooter::exist(source) && !UpgradeSupport::checkUpgradeFlag()) {
387 // Trigger key migration process
388 UpgradeSupport::createUpgradeFlag();
392 engine.reset(new INTERNAL_ENGINE(
393 source, INTERNAL_PATH,
394 ProgressBar([](int v) {
395 ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
396 std::to_string(v).c_str());
401 InternalEncryptionServer::~InternalEncryptionServer()
405 int InternalEncryptionServer::migrateMasterKey(const std::string& dev, const std::string& password)
408 BinaryData masterKey = UpgradeSupport::loadMasterKey(dev);
410 // encrypt the master key with given password
411 return keyServer.changePassword2(dev, masterKey, password);
412 } catch (const runtime::Exception&) {
413 ERROR(SINK, "Failed to load the master key stored during upgrade.");
416 return error::Unknown;
419 int InternalEncryptionServer::setMountPassword(const std::string& password)
421 const std::string& dev = engine->getSource();
423 // check if upgrade flag exists
424 if (UpgradeSupport::checkUpgradeFlag()) {
425 INFO(SINK, "Upgrade flag detected.");
427 int rc = migrateMasterKey(dev, password);
428 if (rc != error::None)
430 UpgradeSupport::removeUpgradeFlag();
433 return keyServer.get(dev, password, mountKey);
436 int InternalEncryptionServer::mount(const std::vector<unsigned char> &mk, unsigned int options)
438 if (mountKey.empty() && mk.empty()) {
439 ERROR(SINK, "You need to set master key first.");
440 return error::NoData;
443 BinaryData key = mk.empty() ? mountKey : mk;
446 if (getState() != State::Encrypted) {
447 ERROR(SINK, "Cannot mount, SD partition's state incorrect.");
448 return error::NoSuchDevice;
451 if (engine->isMounted()) {
452 ERROR(SINK, "Partition already mounted.");
456 INFO(SINK, "Mounting internal storage.");
458 engine->mount(key, getOptions());
460 server.notify("InternalEncryptionServer::mount");
462 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
463 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
464 } catch (runtime::Exception &e) {
465 ERROR(SINK, "Mount failed: " + std::string(e.what()));
466 return error::Unknown;
472 int InternalEncryptionServer::isMounted()
476 ret = engine->isMounted() ? 1 : 0;
477 } catch (runtime::Exception &e) {
478 ERROR(SINK, "Failed to access the mount flag");
479 return error::Unknown;
484 int InternalEncryptionServer::umount()
486 if (getState() != State::Encrypted) {
487 ERROR(SINK, "Cannot umount, partition's state incorrect.");
488 return error::NoSuchDevice;
491 if (!engine->isMounted()) {
492 ERROR(SINK, "Partition already umounted.");
496 INFO(SINK, "Closing all processes using internal storage.");
499 INFO(SINK, "Umounting internal storage.");
500 unmountInternalStorage("/dev/mapper/userdata");
502 } catch (runtime::Exception &e) {
503 ERROR(SINK, "Umount failed: " + std::string(e.what()));
504 return error::Unknown;
510 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
512 if (getState() != State::Unencrypted) {
513 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
514 return error::NoSuchDevice;
517 BinaryData masterKey;
518 int ret = keyServer.get(engine->getSource(), password, masterKey);
519 if (ret != error::None)
522 auto encryptWorker = [masterKey, options, this]() {
524 if (::device_power_request_lock(POWER_LOCK_DISPLAY, 0) != 0)
525 ERROR(SINK, "Failed to request to lock display");
527 showProgressUI("encrypt");
530 runtime::File file("/opt/etc/.odeprogress");
533 std::string source = engine->getSource();
534 auto mntPaths = findMountPointsByDevice(source);
536 if (!mntPaths.empty()) {
537 INFO(SINK, "Closing all processes using internal storage.");
540 INFO(SINK, "Unmounting internal storage.");
541 unmountInternalStorage(source);
544 INFO(SINK, "Encryption started.");
545 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
547 engine->encrypt(masterKey, options);
548 } catch (runtime::Exception &e) {
549 ERROR(SINK, e.what());
550 if (!engine->isStarted()) {
551 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
555 ::reboot(RB_AUTOBOOT);
557 setOptions(options & getSupportedOptions());
559 INFO(SINK, "Encryption completed.");
560 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
561 server.notify("InternalEncryptionServer::mount");
565 INFO(SINK, "Syncing disk and rebooting.");
567 ::reboot(RB_AUTOBOOT);
568 } catch (runtime::Exception &e) {
569 ERROR(SINK, "Encryption failed: " + std::string(e.what()));
573 std::thread asyncWork(encryptWorker);
579 int InternalEncryptionServer::decrypt(const std::string& password)
581 if (getState() != State::Encrypted) {
582 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
583 return error::NoSuchDevice;
586 // check if key migration is needed
587 if (UpgradeSupport::checkUpgradeFlag()) {
588 INFO(SINK, "Upgrade flag detected.");
589 const std::string& dev = engine->getSource();
590 int rc = migrateMasterKey(dev, password);
591 if (rc == error::None)
592 UpgradeSupport::removeUpgradeFlag();
595 BinaryData masterKey;
596 int ret = keyServer.get(engine->getSource(), password, masterKey);
597 if (ret != error::None)
600 auto decryptWorker = [masterKey, this]() {
602 if (::device_power_request_lock(POWER_LOCK_DISPLAY, 0) != 0)
603 ERROR(SINK, "Failed to request to lock display");
605 showProgressUI("decrypt");
608 runtime::File file("/opt/etc/.odeprogress");
611 if (engine->isMounted()) {
612 INFO(SINK, "Closing all processes using internal storage.");
615 INFO(SINK, "Umounting internal storage.");
616 unmountInternalStorage("/dev/mapper/userdata");
620 INFO(SINK, "Decryption started.");
621 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
623 engine->decrypt(masterKey, getOptions());
624 } catch (runtime::Exception &e) {
625 ERROR(SINK, e.what());
626 if (!engine->isStarted()) {
627 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
631 ::reboot(RB_AUTOBOOT);
634 INFO(SINK, "Decryption complete.");
635 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
639 INFO(SINK, "Syncing disk and rebooting.");
641 ::reboot(RB_AUTOBOOT);
642 } catch (runtime::Exception &e) {
643 ERROR(SINK, "Decryption failed: " + std::string(e.what()));
647 std::thread asyncWork(decryptWorker);
653 int InternalEncryptionServer::recovery()
655 int state = getState();
657 if (state == State::Unencrypted)
658 return error::NoSuchDevice;
660 runtime::File file("/opt/.factoryreset");
665 dbus::Connection& systemDBus = dbus::Connection::getSystem();
666 systemDBus.methodcall("org.tizen.system.deviced",
667 "/Org/Tizen/System/DeviceD/Power",
668 "org.tizen.system.deviced.power",
670 -1, "()", "(si)", "reboot", 0);
671 } catch (runtime::Exception &e) {
672 ::reboot(RB_AUTOBOOT);
677 int InternalEncryptionServer::isPasswordInitialized()
679 return keyServer.isInitialized(engine->getSource());
682 int InternalEncryptionServer::initPassword(const std::string& password)
684 return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
687 int InternalEncryptionServer::cleanPassword(const std::string& password)
689 return keyServer.remove(engine->getSource(), password);
692 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
693 const std::string& newPassword)
695 return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
698 int InternalEncryptionServer::verifyPassword(const std::string& password)
700 return keyServer.verifyPassword(engine->getSource(), password);
703 int InternalEncryptionServer::getState()
705 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
707 throw runtime::Exception("Failed to get vconf value.");
710 std::string valueStr(value);
713 if (valueStr == "encrypted")
714 return State::Encrypted;
715 else if (valueStr == "unencrypted")
716 return State::Unencrypted;
717 else if (valueStr == "error_partially_encrypted" || valueStr == "error_partially_decrypted")
718 return State::Corrupted;
720 return State::NotSupported;
723 unsigned int InternalEncryptionServer::getSupportedOptions()
725 return engine->getSupportedOptions();
728 std::string InternalEncryptionServer::getDevicePath() const
730 return engine->getSource();