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"
56 const char *PRIVILEGE_PLATFORM = "http://tizen.org/privilege/internal/default/platform";
58 // watches systemd jobs
61 explicit JobWatch(dbus::Connection& systemDBus);
64 bool waitForJob(const std::string& job);
67 void jobRemoved(const dbus::Variant& parameters);
71 const std::string& job,
72 const std::string& unit,
73 const std::string& result) : id(id), job(job), unit(unit), result(result) {}
80 dbus::Connection::SubscriptionId id;
81 dbus::Connection& systemDBus;
82 std::list<Job> removedJobs;
84 std::condition_variable jobsCv;
87 JobWatch::JobWatch(dbus::Connection& systemDBus) : systemDBus(systemDBus) {
88 auto callback = [this](dbus::Variant parameters) {
89 this->jobRemoved(parameters);
92 id = systemDBus.subscribeSignal("",
93 "/org/freedesktop/systemd1",
94 "org.freedesktop.systemd1.Manager",
99 JobWatch::~JobWatch() {
100 systemDBus.unsubscribeSignal(id);
103 bool JobWatch::waitForJob(const std::string& job) {
105 std::unique_lock<std::mutex> lock(jobsMutex);
107 auto sec = std::chrono::seconds(1);
108 jobsCv.wait_for(lock, 5*sec, [this, &timeout]{
109 if (!removedJobs.empty()) {
116 INFO(SINK, "job: " + job + ", result: time out");
120 while(!removedJobs.empty()) {
121 bool match = (removedJobs.front().job == job);
122 bool done = (removedJobs.front().result == "done");
123 removedJobs.pop_front();
130 void JobWatch::jobRemoved(const dbus::Variant& parameters)
136 parameters.get("(uoss)", &id, &job, &unit, &result);
137 INFO(SINK, "id:" + std::to_string(id) + " job:" + job + " unit:" + unit + " result:" + result);
140 std::lock_guard<std::mutex> guard(jobsMutex);
141 removedJobs.emplace_back(id, job, unit, result);
146 std::string getDecodedPath(const std::string &path, const std::string &prefix)
148 std::string ret = path;
151 pos = ret.find(prefix);
152 if (pos != std::string::npos)
153 ret = ret.substr(prefix.size(), ret.size());
156 while ((pos = ret.find("_", pos)) != std::string::npos) {
157 int a = std::stoi(std::string(1, ret.at(pos+1)), nullptr, 16);
158 int b = std::stoi(std::string(1, ret.at(pos+2)), nullptr, 16);
160 ret.replace(pos, 3, "_");
162 ret.replace(pos, 3, std::string(1, ((a << 4) | b)));
168 void stopSystemdUnits()
170 dbus::Connection& systemDBus = dbus::Connection::getSystem();
171 dbus::VariantIterator iter;
172 std::vector<std::string> preprocessUnits;
173 std::set<std::string> unitsToStop;
175 auto stopUnit = [&systemDBus](const std::string &unit) {
176 JobWatch watch(systemDBus);
177 INFO(SINK, "Stopping unit: " + unit);
178 const char* job = NULL;
180 systemDBus.methodcall("org.freedesktop.systemd1",
181 "/org/freedesktop/systemd1",
182 "org.freedesktop.systemd1.Manager",
184 -1, "(o)", "(ss)", unit.c_str(), "flush").get("(o)", &job);
185 INFO(SINK, "Waiting for job: " + std::string(job));
186 if (!watch.waitForJob(job))
187 ERROR(SINK, "Stopping unit: " + unit + " failed");
188 } catch (runtime::Exception &e) {
189 ERROR(SINK, std::string(e.what()));
194 systemDBus.methodcall("org.freedesktop.systemd1",
195 "/org/freedesktop/systemd1",
196 "org.freedesktop.systemd1.Manager",
198 -1, "(a(ssssssouso))", "").get("(a(ssssssouso))", &iter);
199 } catch (runtime::Exception &e) {
200 INFO(SINK, "Get list of systemd unit : " + std::string(e.what()));
204 unsigned int dataUnit;
207 ret = iter.get("(ssssssouso)", dataStr, dataStr + 1, dataStr + 2,
208 dataStr + 3, dataStr + 4, dataStr + 5,
209 dataStr + 6, &dataUnit, dataStr + 7, dataStr + 8);
213 std::string unitName(dataStr[0]);
214 if (unitName == "security-manager.socket" ||
215 unitName == "connman.socket" ||
216 unitName == "msg-server.socket") {
217 preprocessUnits.insert(preprocessUnits.begin(), unitName);
218 } else if (unitName.compare(0, 5, "user@") == 0 ||
219 unitName == "tlm.service" ||
220 unitName == "resourced.service" ||
221 unitName == "security-manager.service") {
222 preprocessUnits.push_back(unitName);
226 for (auto unit : preprocessUnits) {
230 for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
232 char *unit = nullptr;
233 systemDBus.methodcall("org.freedesktop.systemd1",
234 "/org/freedesktop/systemd1",
235 "org.freedesktop.systemd1.Manager",
237 -1, "(o)", "(u)", (unsigned int)pid)
240 auto unescapedName = getDecodedPath(unit, "/org/freedesktop/systemd1/unit/");
241 unitsToStop.insert(unescapedName);
242 } catch (runtime::Exception &e) {
243 INFO(SINK, "Killing process: " + std::to_string(pid));
244 ::kill(pid, SIGKILL);
248 for (auto unit : unitsToStop) {
253 void showProgressUI(const std::string type)
255 dbus::Connection& systemDBus = dbus::Connection::getSystem();
256 std::string unit("ode-progress-ui@"+type+".service");
258 JobWatch watch(systemDBus);
259 INFO(SINK, "Start unit: " + unit);
261 const char* job = NULL;
262 systemDBus.methodcall("org.freedesktop.systemd1",
263 "/org/freedesktop/systemd1",
264 "org.freedesktop.systemd1.Manager",
266 -1, "(o)", "(ss)", unit.c_str(), "replace").get("(o)", &job);
268 INFO(SINK, "Waiting for job: " + std::string(job));
269 if (!watch.waitForJob(job))
270 ERROR(SINK, "Starting unit: " + unit + " failed");
273 unsigned int getOptions()
275 unsigned int result = 0;
279 ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
281 result |= InternalEncryption::Option::IncludeUnusedRegion;
287 void setOptions(unsigned int options)
291 if (options & InternalEncryption::Option::IncludeUnusedRegion) {
296 ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
299 void execAndWait(const std::string &path, std::vector<std::string> &args)
301 runtime::Process proc(path, args);
302 int ret = proc.execute();
304 ERROR(SINK, path + " failed for " + args.back());
306 ret = proc.waitForFinished();
307 if (ret < 0 || !WIFEXITED(ret) || WEXITSTATUS(ret) != 0)
308 ERROR(SINK, path + " failed for " + args.back());
311 bool isPartitionTerminated(const std::string &partition)
314 const std::string cmd("fuser -m " + partition + " | grep -o '[0-9]*'");
315 char *line = nullptr;
318 FILE *fp = ::popen(cmd.c_str(), "r");
320 ERROR(SINK, "Failed to get processes on partition");
324 if (::getline(&line, &len, fp) != -1)
333 void unmountInternalStorage(const std::string& source)
335 if (::umount2("/opt/usr", MNT_DETACH) == -1) {
336 if (errno != EBUSY && errno != EINVAL) {
337 throw runtime::Exception("umount() error : " + runtime::GetSystemErrorMessage());
343 static const char *fuserPath = "/usr/bin/fuser";
344 std::vector<std::string> args = {
345 fuserPath, "-m", "-k", "-s", "-SIGTERM", source,
347 execAndWait(fuserPath, args);
348 ::usleep((useconds_t)((unsigned int)(500)*1000));
350 args[4] = "-SIGKILL";
351 execAndWait(fuserPath, args);
352 ::usleep((useconds_t)((unsigned int)(200)*1000));
353 } while (!isPartitionTerminated(source));
358 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv,
363 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
364 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)(std::vector<unsigned char>, unsigned int));
365 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
366 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::isMounted)());
367 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
368 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
369 server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
370 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::recovery)());
371 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
372 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
373 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
374 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
375 server.expose(this, "", (int)(InternalEncryptionServer::getState)());
376 server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
377 server.expose(this, "", (std::string)(InternalEncryptionServer::getDevicePath)());
379 server.createNotification("InternalEncryptionServer::mount");
381 std::string source = findDevPath();
383 engine.reset(new INTERNAL_ENGINE(
384 source, INTERNAL_PATH,
385 ProgressBar([](int v) {
386 ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
387 std::to_string(v).c_str());
392 InternalEncryptionServer::~InternalEncryptionServer()
396 int InternalEncryptionServer::setMountPassword(const std::string& password)
398 const std::string& dev = engine->getSource();
400 // check if upgrade flag exists
401 if(UpgradeSupport::removeUpgradeFlag()) {
402 INFO("Upgrade flag detected.");
403 // try to load the master key
405 mountKey = UpgradeSupport::loadMasterKey(dev);
407 // encrypt the master key with given password
408 return keyServer.changePassword2(dev, mountKey, password);
409 } catch (const runtime::Exception&) {
410 INFO("Failed to load the master key stored during upgrade.");
414 return keyServer.get(dev, password, mountKey);
417 int InternalEncryptionServer::mount(const std::vector<unsigned char> &mk, unsigned int options)
419 if (mountKey.empty() && mk.empty()) {
420 ERROR(SINK, "You need to set master key first.");
421 return error::NoData;
424 BinaryData key = mk.empty() ? mountKey : mk;
427 if (getState() != State::Encrypted) {
428 INFO(SINK, "Cannot mount, SD partition's state incorrect.");
429 return error::NoSuchDevice;
432 if (engine->isMounted()) {
433 INFO(SINK, "Partition already mounted.");
437 INFO(SINK, "Mounting internal storage.");
439 engine->mount(key, getOptions());
441 server.notify("InternalEncryptionServer::mount");
443 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
444 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
445 } catch (runtime::Exception &e) {
446 ERROR(SINK, "Mount failed: " + std::string(e.what()));
447 return error::Unknown;
453 int InternalEncryptionServer::isMounted()
457 ret = engine->isMounted() ? 1 : 0;
458 } catch (runtime::Exception &e) {
459 ERROR(SINK, "Failed to access the mount flag");
460 return error::Unknown;
465 int InternalEncryptionServer::umount()
467 if (getState() != State::Encrypted) {
468 ERROR(SINK, "Cannot umount, partition's state incorrect.");
469 return error::NoSuchDevice;
472 if (!engine->isMounted()) {
473 INFO(SINK, "Partition already umounted.");
477 INFO(SINK, "Closing all processes using internal storage.");
480 INFO(SINK, "Umounting internal storage.");
481 unmountInternalStorage("/dev/mapper/userdata");
483 } catch (runtime::Exception &e) {
484 ERROR(SINK, "Umount failed: " + std::string(e.what()));
485 return error::Unknown;
491 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
493 if (getState() != State::Unencrypted) {
494 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
495 return error::NoSuchDevice;
498 BinaryData masterKey;
499 int ret = keyServer.get(engine->getSource(), password, masterKey);
500 if (ret != error::None)
503 auto encryptWorker = [masterKey, options, this]() {
505 if (::device_power_request_lock(POWER_LOCK_DISPLAY, 0) != 0)
506 ERROR(SINK, "Failed to request to lock display");
508 showProgressUI("encrypt");
511 runtime::File file("/opt/etc/.odeprogress");
514 std::string source = engine->getSource();
515 auto mntPaths = findMountPointsByDevice(source);
517 if (!mntPaths.empty()) {
518 INFO(SINK, "Closing all processes using internal storage.");
521 INFO(SINK, "Unmounting internal storage.");
522 unmountInternalStorage(source);
525 INFO(SINK, "Encryption started.");
526 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
528 engine->encrypt(masterKey, options);
529 } catch (runtime::Exception &e) {
530 ERROR(SINK, e.what());
531 if (!engine->isStarted()) {
532 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
536 ::reboot(RB_AUTOBOOT);
538 setOptions(options & getSupportedOptions());
540 INFO(SINK, "Encryption completed.");
541 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
542 server.notify("InternalEncryptionServer::mount");
546 INFO(SINK, "Syncing disk and rebooting.");
548 ::reboot(RB_AUTOBOOT);
549 } catch (runtime::Exception &e) {
550 ERROR(SINK, "Encryption failed: " + std::string(e.what()));
554 std::thread asyncWork(encryptWorker);
560 int InternalEncryptionServer::decrypt(const std::string& password)
562 if (getState() != State::Encrypted) {
563 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
564 return error::NoSuchDevice;
567 BinaryData masterKey;
568 int ret = keyServer.get(engine->getSource(), password, masterKey);
569 if (ret != error::None)
572 auto decryptWorker = [masterKey, this]() {
574 if (::device_power_request_lock(POWER_LOCK_DISPLAY, 0) != 0)
575 ERROR(SINK, "Failed to request to lock display");
577 showProgressUI("decrypt");
580 runtime::File file("/opt/etc/.odeprogress");
583 if (engine->isMounted()) {
584 INFO(SINK, "Closing all processes using internal storage.");
587 INFO(SINK, "Umounting internal storage.");
588 unmountInternalStorage("/dev/mapper/userdata");
592 INFO(SINK, "Decryption started.");
593 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
595 engine->decrypt(masterKey, getOptions());
596 } catch (runtime::Exception &e) {
597 ERROR(SINK, e.what());
598 if (!engine->isStarted()) {
599 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
603 ::reboot(RB_AUTOBOOT);
606 INFO(SINK, "Decryption complete.");
607 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
611 INFO(SINK, "Syncing disk and rebooting.");
613 ::reboot(RB_AUTOBOOT);
614 } catch (runtime::Exception &e) {
615 ERROR(SINK, "Decryption failed: " + std::string(e.what()));
619 std::thread asyncWork(decryptWorker);
625 int InternalEncryptionServer::recovery()
627 int state = getState();
629 if (state == State::Unencrypted)
630 return error::NoSuchDevice;
632 runtime::File file("/opt/.factoryreset");
637 dbus::Connection& systemDBus = dbus::Connection::getSystem();
638 systemDBus.methodcall("org.tizen.system.deviced",
639 "/Org/Tizen/System/DeviceD/Power",
640 "org.tizen.system.deviced.power",
642 -1, "()", "(si)", "reboot", 0);
643 } catch (runtime::Exception &e) {
644 ::reboot(RB_AUTOBOOT);
649 int InternalEncryptionServer::isPasswordInitialized()
651 return keyServer.isInitialized(engine->getSource());
654 int InternalEncryptionServer::initPassword(const std::string& password)
656 return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
659 int InternalEncryptionServer::cleanPassword(const std::string& password)
661 return keyServer.remove(engine->getSource(), password);
664 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
665 const std::string& newPassword)
667 return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
670 int InternalEncryptionServer::verifyPassword(const std::string& password)
672 return keyServer.verifyPassword(engine->getSource(), password);
675 int InternalEncryptionServer::getState()
677 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
679 throw runtime::Exception("Failed to get vconf value.");
682 std::string valueStr(value);
685 if (valueStr == "encrypted")
686 return State::Encrypted;
687 else if (valueStr == "unencrypted")
688 return State::Unencrypted;
689 else if (valueStr == "error_partially_encrypted" || valueStr == "error_partially_decrypted")
690 return State::Corrupted;
692 return State::NotSupported;
695 unsigned int InternalEncryptionServer::getSupportedOptions()
697 return engine->getSupportedOptions();
700 std::string InternalEncryptionServer::getDevicePath() const
702 return engine->getSource();