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";
56 // watches systemd jobs
59 explicit JobWatch(dbus::Connection& systemDBus);
62 bool waitForJob(const std::string& job);
65 void jobRemoved(const dbus::Variant& parameters);
69 const std::string& job,
70 const std::string& unit,
71 const std::string& result) : id(id), job(job), unit(unit), result(result) {}
78 dbus::Connection::SubscriptionId id;
79 dbus::Connection& systemDBus;
80 std::list<Job> removedJobs;
82 std::condition_variable jobsCv;
85 JobWatch::JobWatch(dbus::Connection& systemDBus) : systemDBus(systemDBus) {
86 auto callback = [this](dbus::Variant parameters) {
87 this->jobRemoved(parameters);
90 id = systemDBus.subscribeSignal("",
91 "/org/freedesktop/systemd1",
92 "org.freedesktop.systemd1.Manager",
97 JobWatch::~JobWatch() {
98 systemDBus.unsubscribeSignal(id);
101 bool JobWatch::waitForJob(const std::string& job) {
103 std::unique_lock<std::mutex> lock(jobsMutex);
104 jobsCv.wait(lock, [this]{ return !removedJobs.empty(); });
106 while(!removedJobs.empty()) {
107 bool match = (removedJobs.front().job == job);
108 bool done = (removedJobs.front().result == "done");
109 removedJobs.pop_front();
116 void JobWatch::jobRemoved(const dbus::Variant& parameters)
122 parameters.get("(uoss)", &id, &job, &unit, &result);
123 INFO(SINK, "id:" + std::to_string(id) + " job:" + job + " unit:" + unit + " result:" + result);
126 std::lock_guard<std::mutex> guard(jobsMutex);
127 removedJobs.emplace_back(id, job, unit, result);
132 void stopKnownSystemdUnits()
134 std::vector<std::string> knownSystemdUnits;
135 dbus::Connection& systemDBus = dbus::Connection::getSystem();
136 dbus::VariantIterator iter;
138 systemDBus.methodcall("org.freedesktop.systemd1",
139 "/org/freedesktop/systemd1",
140 "org.freedesktop.systemd1.Manager",
142 -1, "(a(ssssssouso))", "")
143 .get("(a(ssssssouso))", &iter);
146 unsigned int dataUint;
150 ret = iter.get("(ssssssouso)", dataStr, dataStr + 1, dataStr + 2,
151 dataStr + 3, dataStr + 4, dataStr + 5,
152 dataStr + 6, &dataUint, dataStr + 7,
159 std::string unit(dataStr[0]);
160 if (unit == "security-manager.socket" ||
161 unit == "connman.socket") {
162 knownSystemdUnits.insert(knownSystemdUnits.begin(), unit);
163 } else if (unit.compare(0, 5, "user@") == 0 ||
164 unit == "tlm.service" ||
165 unit == "resourced.service" ||
166 unit == "security-manager.service") {
167 knownSystemdUnits.push_back(unit);
171 JobWatch watch(systemDBus);
173 for (const std::string& unit : knownSystemdUnits) {
174 INFO(SINK, "Stopping unit: " + unit);
175 const char* job = NULL;
176 systemDBus.methodcall("org.freedesktop.systemd1",
177 "/org/freedesktop/systemd1",
178 "org.freedesktop.systemd1.Manager",
180 -1, "(o)", "(ss)", unit.c_str(), "flush").get("(o)", &job);
181 INFO(SINK, "Waiting for job: " + std::string(job));
182 if (!watch.waitForJob(job))
183 throw runtime::Exception("Stopping unit: " + unit + " failed");
187 std::string getDecodedPath(const std::string &path, const std::string &prefix)
189 std::string ret = path;
192 pos = ret.find(prefix);
193 if (pos != std::string::npos)
194 ret = ret.substr(prefix.size(), ret.size());
197 while ((pos = ret.find("_", pos)) != std::string::npos) {
198 int a = std::stoi(std::string(1, ret.at(pos+1)), nullptr, 16);
199 int b = std::stoi(std::string(1, ret.at(pos+2)), nullptr, 16);
201 ret.replace(pos, 3, "_");
203 ret.replace(pos, 3, std::string(1, ((a << 4) | b)));
209 void stopDependedSystemdUnits()
211 dbus::Connection& systemDBus = dbus::Connection::getSystem();
212 std::set<std::string> unitsToStop;
215 for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
217 char *unit = nullptr;
218 systemDBus.methodcall("org.freedesktop.systemd1",
219 "/org/freedesktop/systemd1",
220 "org.freedesktop.systemd1.Manager",
222 -1, "(o)", "(u)", (unsigned int)pid)
225 auto unescapedName = getDecodedPath(unit, "/org/freedesktop/systemd1/unit/");
226 if (unescapedName == "samsung-log-mgr.service")
229 unitsToStop.insert(unescapedName);
230 } catch (runtime::Exception &e) {
231 INFO(SINK, "Killing process: " + std::to_string(pid));
232 ::kill(pid, SIGKILL);
236 JobWatch watch(systemDBus);
238 for (const std::string& unit : unitsToStop) {
239 INFO(SINK, "Stopping unit: " + unit);
240 const char* job = NULL;
241 systemDBus.methodcall("org.freedesktop.systemd1",
242 "/org/freedesktop/systemd1",
243 "org.freedesktop.systemd1.Manager",
245 -1, "(o)", "(ss)", unit.c_str(), "flush").get("(o)", &job);
246 INFO(SINK, "Waiting for job: " + std::string(job));
247 if (!watch.waitForJob(job))
248 throw runtime::Exception("Stopping unit: " + unit + " failed");
251 if (::umount2("/sys/fs/cgroup", MNT_FORCE | MNT_DETACH) != 0)
252 INFO(SINK, "Failed to unmount cgroup");
258 void showProgressUI(const std::string type)
260 dbus::Connection& systemDBus = dbus::Connection::getSystem();
261 std::string unit("ode-progress-ui@"+type+".service");
263 JobWatch watch(systemDBus);
264 INFO(SINK, "Start unit: " + unit);
266 const char* job = NULL;
267 systemDBus.methodcall("org.freedesktop.systemd1",
268 "/org/freedesktop/systemd1",
269 "org.freedesktop.systemd1.Manager",
271 -1, "(o)", "(ss)", unit.c_str(), "replace").get("(o)", &job);
273 INFO(SINK, "Waiting for job: " + std::string(job));
274 if (!watch.waitForJob(job))
275 throw runtime::Exception("Starting unit: " + unit + " failed");
278 unsigned int getOptions()
280 unsigned int result = 0;
284 ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
286 result |= InternalEncryption::Option::IncludeUnusedRegion;
292 void setOptions(unsigned int options)
296 if (options & InternalEncryption::Option::IncludeUnusedRegion) {
301 ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
304 void unmountInternalStorage(const std::string& source)
307 auto mntPaths = findMountPointsByDevice(source);
311 bool unmounted = true;
312 for(const auto& path : mntPaths) {
313 INFO(SINK, "Unmounting " + path);
314 if (::umount(path.c_str()) == -1) {
315 // If it's busy or was already unmounted ignore the error
316 if (errno != EBUSY && errno != EINVAL) {
317 throw runtime::Exception("umount() error: " + runtime::GetSystemErrorMessage());
323 stopDependedSystemdUnits();
329 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv,
334 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
335 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)(std::vector<unsigned char>, unsigned int));
336 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
337 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
338 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
339 server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
340 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::recovery)());
341 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
342 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
343 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
344 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
345 server.expose(this, "", (int)(InternalEncryptionServer::getState)());
346 server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
347 server.expose(this, "", (std::string)(InternalEncryptionServer::getDevicePath)());
349 server.createNotification("InternalEncryptionServer::mount");
351 std::string source = findDevPath();
353 engine.reset(new INTERNAL_ENGINE(
354 source, INTERNAL_PATH,
355 ProgressBar([](int v) {
356 ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
357 std::to_string(v).c_str());
362 InternalEncryptionServer::~InternalEncryptionServer()
366 int InternalEncryptionServer::setMountPassword(const std::string& password)
368 return keyServer.get(engine->getSource(), password, mountKey);
371 int InternalEncryptionServer::mount(const std::vector<unsigned char> &mk, unsigned int options)
373 if (mountKey.empty() && mk.empty()) {
374 ERROR(SINK, "You need to set master key first.");
375 return error::NoData;
378 BinaryData key = mk.empty() ? mountKey : mk;
381 if (getState() != State::Encrypted) {
382 INFO(SINK, "Cannot mount, SD partition's state incorrect.");
383 return error::NoSuchDevice;
386 if (engine->isMounted()) {
387 INFO(SINK, "Partition already mounted.");
391 INFO(SINK, "Mounting internal storage.");
393 engine->mount(key, getOptions());
395 server.notify("InternalEncryptionServer::mount");
397 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
398 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
399 } catch (runtime::Exception &e) {
400 ERROR(SINK, "Mount failed: " + std::string(e.what()));
401 return error::Unknown;
407 int InternalEncryptionServer::umount()
409 if (getState() != State::Encrypted) {
410 ERROR(SINK, "Cannot umount, partition's state incorrect.");
411 return error::NoSuchDevice;
414 if (!engine->isMounted()) {
415 INFO(SINK, "Partition already umounted.");
419 INFO(SINK, "Closing all processes using internal storage.");
421 stopDependedSystemdUnits();
422 INFO(SINK, "Umounting internal storage.");
424 } catch (runtime::Exception &e) {
425 ERROR(SINK, "Umount failed: " + std::string(e.what()));
426 return error::Unknown;
432 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
434 if (getState() != State::Unencrypted) {
435 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
436 return error::NoSuchDevice;
439 BinaryData masterKey;
440 int ret = keyServer.get(engine->getSource(), password, masterKey);
441 if (ret != error::None)
444 auto encryptWorker = [masterKey, options, this]() {
446 showProgressUI("encrypt");
449 runtime::File file("/opt/etc/.odeprogress");
452 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
453 stopKnownSystemdUnits();
455 std::string source = engine->getSource();
456 auto mntPaths = findMountPointsByDevice(source);
458 if (!mntPaths.empty()) {
459 INFO(SINK, "Closing all processes using internal storage.");
460 stopDependedSystemdUnits();
462 INFO(SINK, "Unmounting internal storage.");
463 unmountInternalStorage(source);
466 INFO(SINK, "Encryption started.");
467 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
468 engine->encrypt(masterKey, options);
469 setOptions(options & getSupportedOptions());
471 INFO(SINK, "Encryption completed.");
472 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
473 server.notify("InternalEncryptionServer::mount");
477 INFO(SINK, "Syncing disk and rebooting.");
479 ::reboot(RB_AUTOBOOT);
480 } catch (runtime::Exception &e) {
481 ERROR(SINK, "Encryption failed: " + std::string(e.what()));
485 std::thread asyncWork(encryptWorker);
491 int InternalEncryptionServer::decrypt(const std::string& password)
493 if (getState() != State::Encrypted) {
494 ERROR(SINK, "Cannot decrypt, 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 decryptWorker = [masterKey, this]() {
505 showProgressUI("decrypt");
508 runtime::File file("/opt/etc/.odeprogress");
511 if (engine->isMounted()) {
512 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
513 stopKnownSystemdUnits();
514 INFO(SINK, "Closing all processes using internal storage.");
515 stopDependedSystemdUnits();
517 INFO(SINK, "Umounting internal storage.");
522 } catch (runtime::Exception& e) {
523 stopDependedSystemdUnits();
528 INFO(SINK, "Decryption started.");
529 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
530 engine->decrypt(masterKey, getOptions());
532 INFO(SINK, "Decryption complete.");
533 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
537 INFO(SINK, "Syncing disk and rebooting.");
539 ::reboot(RB_AUTOBOOT);
540 } catch (runtime::Exception &e) {
541 ERROR(SINK, "Decryption failed: " + std::string(e.what()));
545 std::thread asyncWork(decryptWorker);
551 int InternalEncryptionServer::recovery()
553 int state = getState();
555 if (state == State::Unencrypted)
556 return error::NoSuchDevice;
558 runtime::File file("/opt/.factoryreset");
563 dbus::Connection& systemDBus = dbus::Connection::getSystem();
564 systemDBus.methodcall("org.tizen.system.deviced",
565 "/Org/Tizen/System/DeviceD/Power",
566 "org.tizen.system.deviced.power",
568 -1, "()", "(si)", "reboot", 0);
569 } catch (runtime::Exception &e) {
570 ::reboot(RB_AUTOBOOT);
575 int InternalEncryptionServer::isPasswordInitialized()
577 return keyServer.isInitialized(engine->getSource());
580 int InternalEncryptionServer::initPassword(const std::string& password)
582 return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
585 int InternalEncryptionServer::cleanPassword(const std::string& password)
587 return keyServer.remove(engine->getSource(), password);
590 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
591 const std::string& newPassword)
593 return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
596 int InternalEncryptionServer::verifyPassword(const std::string& password)
598 return keyServer.verifyPassword(engine->getSource(), password);
601 int InternalEncryptionServer::getState()
603 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
605 throw runtime::Exception("Failed to get vconf value.");
608 std::string valueStr(value);
611 if (valueStr == "encrypted")
612 return State::Encrypted;
613 else if (valueStr == "unencrypted")
614 return State::Unencrypted;
615 else if (valueStr == "error_partially_encrypted" || valueStr == "error_partially_decrypted")
616 return State::Corrupted;
618 return State::Invalid;
621 unsigned int InternalEncryptionServer::getSupportedOptions()
623 return engine->getSupportedOptions();
626 std::string InternalEncryptionServer::getDevicePath() const
628 return engine->getSource();