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 <klay/process.h>
36 #include <klay/file-user.h>
37 #include <klay/filesystem.h>
38 #include <klay/dbus/connection.h>
39 #include <klay/error.h>
43 #include "progress-bar.h"
44 #include "rmi/common.h"
46 #include "ext4-tool.h"
47 #include "internal-encryption.h"
48 #include "internal-encryption-common.h"
54 const char *PRIVILEGE_PLATFORM = "http://tizen.org/privilege/internal/default/platform";
55 const std::vector<std::string> blackListSystemdUnits = {
56 "samsung-log-mgr.service",
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);
107 jobsCv.wait(lock, [this]{ return !removedJobs.empty(); });
109 while(!removedJobs.empty()) {
110 bool match = (removedJobs.front().job == job);
111 bool done = (removedJobs.front().result == "done");
112 removedJobs.pop_front();
119 void JobWatch::jobRemoved(const dbus::Variant& parameters)
125 parameters.get("(uoss)", &id, &job, &unit, &result);
126 INFO(SINK, "id:" + std::to_string(id) + " job:" + job + " unit:" + unit + " result:" + result);
129 std::lock_guard<std::mutex> guard(jobsMutex);
130 removedJobs.emplace_back(id, job, unit, result);
135 void stopKnownSystemdUnits()
137 std::vector<std::string> knownSystemdUnits;
138 dbus::Connection& systemDBus = dbus::Connection::getSystem();
139 dbus::VariantIterator iter;
141 systemDBus.methodcall("org.freedesktop.systemd1",
142 "/org/freedesktop/systemd1",
143 "org.freedesktop.systemd1.Manager",
145 -1, "(a(ssssssouso))", "")
146 .get("(a(ssssssouso))", &iter);
149 unsigned int dataUint;
153 ret = iter.get("(ssssssouso)", dataStr, dataStr + 1, dataStr + 2,
154 dataStr + 3, dataStr + 4, dataStr + 5,
155 dataStr + 6, &dataUint, dataStr + 7,
162 std::string unit(dataStr[0]);
163 if (unit == "security-manager.socket" ||
164 unit == "connman.socket") {
165 knownSystemdUnits.insert(knownSystemdUnits.begin(), unit);
166 } else if (unit.compare(0, 5, "user@") == 0 ||
167 unit == "tlm.service" ||
168 unit == "resourced.service" ||
169 unit == "security-manager.service") {
170 knownSystemdUnits.push_back(unit);
174 JobWatch watch(systemDBus);
176 for (const std::string& unit : knownSystemdUnits) {
177 INFO(SINK, "Stopping unit: " + unit);
178 const char* job = NULL;
179 systemDBus.methodcall("org.freedesktop.systemd1",
180 "/org/freedesktop/systemd1",
181 "org.freedesktop.systemd1.Manager",
183 -1, "(o)", "(ss)", unit.c_str(), "flush").get("(o)", &job);
184 INFO(SINK, "Waiting for job: " + std::string(job));
185 if (!watch.waitForJob(job))
186 throw runtime::Exception("Stopping unit: " + unit + " failed");
190 std::string getDecodedPath(const std::string &path, const std::string &prefix)
192 std::string ret = path;
195 pos = ret.find(prefix);
196 if (pos != std::string::npos)
197 ret = ret.substr(prefix.size(), ret.size());
200 while ((pos = ret.find("_", pos)) != std::string::npos) {
201 int a = std::stoi(std::string(1, ret.at(pos+1)), nullptr, 16);
202 int b = std::stoi(std::string(1, ret.at(pos+2)), nullptr, 16);
204 ret.replace(pos, 3, "_");
206 ret.replace(pos, 3, std::string(1, ((a << 4) | b)));
212 void stopDependedSystemdUnits()
214 dbus::Connection& systemDBus = dbus::Connection::getSystem();
215 std::set<std::string> unitsToStop;
217 for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
219 char *unit = nullptr;
220 systemDBus.methodcall("org.freedesktop.systemd1",
221 "/org/freedesktop/systemd1",
222 "org.freedesktop.systemd1.Manager",
224 -1, "(o)", "(u)", (unsigned int)pid)
227 auto unescapedName = getDecodedPath(unit, "/org/freedesktop/systemd1/unit/");
228 unitsToStop.insert(unescapedName);
229 } catch (runtime::Exception &e) {
230 INFO(SINK, "Killing process: " + std::to_string(pid));
231 ::kill(pid, SIGKILL);
235 JobWatch watch(systemDBus);
236 for (auto unit : blackListSystemdUnits) {
237 unitsToStop.erase(unitsToStop.find(unit));
240 for (const std::string& unit : unitsToStop) {
241 INFO(SINK, "Stopping unit: " + unit);
242 const char* job = NULL;
243 systemDBus.methodcall("org.freedesktop.systemd1",
244 "/org/freedesktop/systemd1",
245 "org.freedesktop.systemd1.Manager",
247 -1, "(o)", "(ss)", unit.c_str(), "flush").get("(o)", &job);
248 INFO(SINK, "Waiting for job: " + std::string(job));
249 if (!watch.waitForJob(job))
250 throw runtime::Exception("Stopping unit: " + unit + " failed");
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 throw runtime::Exception("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::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 return keyServer.get(engine->getSource(), password, mountKey);
401 int InternalEncryptionServer::mount(const std::vector<unsigned char> &mk, unsigned int options)
403 if (mountKey.empty() && mk.empty()) {
404 ERROR(SINK, "You need to set master key first.");
405 return error::NoData;
408 BinaryData key = mk.empty() ? mountKey : mk;
411 if (getState() != State::Encrypted) {
412 INFO(SINK, "Cannot mount, SD partition's state incorrect.");
413 return error::NoSuchDevice;
416 if (engine->isMounted()) {
417 INFO(SINK, "Partition already mounted.");
421 INFO(SINK, "Mounting internal storage.");
423 engine->mount(key, getOptions());
425 server.notify("InternalEncryptionServer::mount");
427 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
428 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
429 } catch (runtime::Exception &e) {
430 ERROR(SINK, "Mount failed: " + std::string(e.what()));
431 return error::Unknown;
437 int InternalEncryptionServer::umount()
439 if (getState() != State::Encrypted) {
440 ERROR(SINK, "Cannot umount, partition's state incorrect.");
441 return error::NoSuchDevice;
444 if (!engine->isMounted()) {
445 INFO(SINK, "Partition already umounted.");
449 INFO(SINK, "Closing all processes using internal storage.");
451 stopKnownSystemdUnits();
452 stopDependedSystemdUnits();
453 INFO(SINK, "Umounting internal storage.");
454 unmountInternalStorage("/dev/mapper/userdata");
456 } catch (runtime::Exception &e) {
457 ERROR(SINK, "Umount failed: " + std::string(e.what()));
458 return error::Unknown;
464 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
466 if (getState() != State::Unencrypted) {
467 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
468 return error::NoSuchDevice;
471 BinaryData masterKey;
472 int ret = keyServer.get(engine->getSource(), password, masterKey);
473 if (ret != error::None)
476 auto encryptWorker = [masterKey, options, this]() {
478 showProgressUI("encrypt");
481 runtime::File file("/opt/etc/.odeprogress");
484 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
485 stopKnownSystemdUnits();
487 std::string source = engine->getSource();
488 auto mntPaths = findMountPointsByDevice(source);
490 if (!mntPaths.empty()) {
491 INFO(SINK, "Closing all processes using internal storage.");
492 stopDependedSystemdUnits();
494 INFO(SINK, "Unmounting internal storage.");
495 unmountInternalStorage(source);
498 INFO(SINK, "Encryption started.");
499 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
500 engine->encrypt(masterKey, options);
501 setOptions(options & getSupportedOptions());
503 INFO(SINK, "Encryption completed.");
504 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
505 server.notify("InternalEncryptionServer::mount");
509 INFO(SINK, "Syncing disk and rebooting.");
511 ::reboot(RB_AUTOBOOT);
512 } catch (runtime::Exception &e) {
513 ERROR(SINK, "Encryption failed: " + std::string(e.what()));
517 std::thread asyncWork(encryptWorker);
523 int InternalEncryptionServer::decrypt(const std::string& password)
525 if (getState() != State::Encrypted) {
526 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
527 return error::NoSuchDevice;
530 BinaryData masterKey;
531 int ret = keyServer.get(engine->getSource(), password, masterKey);
532 if (ret != error::None)
535 auto decryptWorker = [masterKey, this]() {
537 showProgressUI("decrypt");
540 runtime::File file("/opt/etc/.odeprogress");
543 if (engine->isMounted()) {
544 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
545 stopKnownSystemdUnits();
546 INFO(SINK, "Closing all processes using internal storage.");
547 stopDependedSystemdUnits();
549 INFO(SINK, "Umounting internal storage.");
550 unmountInternalStorage("/dev/mapper/userdata");
554 INFO(SINK, "Decryption started.");
555 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
556 engine->decrypt(masterKey, getOptions());
558 INFO(SINK, "Decryption complete.");
559 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
563 INFO(SINK, "Syncing disk and rebooting.");
565 ::reboot(RB_AUTOBOOT);
566 } catch (runtime::Exception &e) {
567 ERROR(SINK, "Decryption failed: " + std::string(e.what()));
571 std::thread asyncWork(decryptWorker);
577 int InternalEncryptionServer::recovery()
579 int state = getState();
581 if (state == State::Unencrypted)
582 return error::NoSuchDevice;
584 runtime::File file("/opt/.factoryreset");
589 dbus::Connection& systemDBus = dbus::Connection::getSystem();
590 systemDBus.methodcall("org.tizen.system.deviced",
591 "/Org/Tizen/System/DeviceD/Power",
592 "org.tizen.system.deviced.power",
594 -1, "()", "(si)", "reboot", 0);
595 } catch (runtime::Exception &e) {
596 ::reboot(RB_AUTOBOOT);
601 int InternalEncryptionServer::isPasswordInitialized()
603 return keyServer.isInitialized(engine->getSource());
606 int InternalEncryptionServer::initPassword(const std::string& password)
608 return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
611 int InternalEncryptionServer::cleanPassword(const std::string& password)
613 return keyServer.remove(engine->getSource(), password);
616 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
617 const std::string& newPassword)
619 return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
622 int InternalEncryptionServer::verifyPassword(const std::string& password)
624 return keyServer.verifyPassword(engine->getSource(), password);
627 int InternalEncryptionServer::getState()
629 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
631 throw runtime::Exception("Failed to get vconf value.");
634 std::string valueStr(value);
637 if (valueStr == "encrypted")
638 return State::Encrypted;
639 else if (valueStr == "unencrypted")
640 return State::Unencrypted;
641 else if (valueStr == "error_partially_encrypted" || valueStr == "error_partially_decrypted")
642 return State::Corrupted;
644 return State::Invalid;
647 unsigned int InternalEncryptionServer::getSupportedOptions()
649 return engine->getSupportedOptions();
652 std::string InternalEncryptionServer::getDevicePath() const
654 return engine->getSource();