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"
49 #include "upgrade-support.h"
55 const char *PRIVILEGE_PLATFORM = "http://tizen.org/privilege/internal/default/platform";
56 const std::vector<std::string> blackListSystemdUnits = {
57 "samsung-log-mgr.service",
60 // watches systemd jobs
63 explicit JobWatch(dbus::Connection& systemDBus);
66 bool waitForJob(const std::string& job);
69 void jobRemoved(const dbus::Variant& parameters);
73 const std::string& job,
74 const std::string& unit,
75 const std::string& result) : id(id), job(job), unit(unit), result(result) {}
82 dbus::Connection::SubscriptionId id;
83 dbus::Connection& systemDBus;
84 std::list<Job> removedJobs;
86 std::condition_variable jobsCv;
89 JobWatch::JobWatch(dbus::Connection& systemDBus) : systemDBus(systemDBus) {
90 auto callback = [this](dbus::Variant parameters) {
91 this->jobRemoved(parameters);
94 id = systemDBus.subscribeSignal("",
95 "/org/freedesktop/systemd1",
96 "org.freedesktop.systemd1.Manager",
101 JobWatch::~JobWatch() {
102 systemDBus.unsubscribeSignal(id);
105 bool JobWatch::waitForJob(const std::string& job) {
107 std::unique_lock<std::mutex> lock(jobsMutex);
108 jobsCv.wait(lock, [this]{ return !removedJobs.empty(); });
110 while(!removedJobs.empty()) {
111 bool match = (removedJobs.front().job == job);
112 bool done = (removedJobs.front().result == "done");
113 removedJobs.pop_front();
120 void JobWatch::jobRemoved(const dbus::Variant& parameters)
126 parameters.get("(uoss)", &id, &job, &unit, &result);
127 INFO(SINK, "id:" + std::to_string(id) + " job:" + job + " unit:" + unit + " result:" + result);
130 std::lock_guard<std::mutex> guard(jobsMutex);
131 removedJobs.emplace_back(id, job, unit, result);
136 void stopKnownSystemdUnits()
138 std::vector<std::string> knownSystemdUnits;
139 dbus::Connection& systemDBus = dbus::Connection::getSystem();
140 dbus::VariantIterator iter;
142 systemDBus.methodcall("org.freedesktop.systemd1",
143 "/org/freedesktop/systemd1",
144 "org.freedesktop.systemd1.Manager",
146 -1, "(a(ssssssouso))", "")
147 .get("(a(ssssssouso))", &iter);
150 unsigned int dataUint;
154 ret = iter.get("(ssssssouso)", dataStr, dataStr + 1, dataStr + 2,
155 dataStr + 3, dataStr + 4, dataStr + 5,
156 dataStr + 6, &dataUint, dataStr + 7,
163 std::string unit(dataStr[0]);
164 if (unit == "security-manager.socket" ||
165 unit == "connman.socket") {
166 knownSystemdUnits.insert(knownSystemdUnits.begin(), unit);
167 } else if (unit.compare(0, 5, "user@") == 0 ||
168 unit == "tlm.service" ||
169 unit == "resourced.service" ||
170 unit == "security-manager.service") {
171 knownSystemdUnits.push_back(unit);
175 JobWatch watch(systemDBus);
177 for (const std::string& unit : knownSystemdUnits) {
178 INFO(SINK, "Stopping unit: " + unit);
179 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 throw runtime::Exception("Stopping unit: " + unit + " failed");
191 std::string getDecodedPath(const std::string &path, const std::string &prefix)
193 std::string ret = path;
196 pos = ret.find(prefix);
197 if (pos != std::string::npos)
198 ret = ret.substr(prefix.size(), ret.size());
201 while ((pos = ret.find("_", pos)) != std::string::npos) {
202 int a = std::stoi(std::string(1, ret.at(pos+1)), nullptr, 16);
203 int b = std::stoi(std::string(1, ret.at(pos+2)), nullptr, 16);
205 ret.replace(pos, 3, "_");
207 ret.replace(pos, 3, std::string(1, ((a << 4) | b)));
213 void stopDependedSystemdUnits()
215 dbus::Connection& systemDBus = dbus::Connection::getSystem();
216 std::set<std::string> unitsToStop;
218 for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
220 char *unit = nullptr;
221 systemDBus.methodcall("org.freedesktop.systemd1",
222 "/org/freedesktop/systemd1",
223 "org.freedesktop.systemd1.Manager",
225 -1, "(o)", "(u)", (unsigned int)pid)
228 auto unescapedName = getDecodedPath(unit, "/org/freedesktop/systemd1/unit/");
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);
237 for (auto unit : blackListSystemdUnits) {
238 unitsToStop.erase(unitsToStop.find(unit));
241 for (const std::string& unit : unitsToStop) {
242 INFO(SINK, "Stopping unit: " + unit);
243 const char* job = NULL;
244 systemDBus.methodcall("org.freedesktop.systemd1",
245 "/org/freedesktop/systemd1",
246 "org.freedesktop.systemd1.Manager",
248 -1, "(o)", "(ss)", unit.c_str(), "flush").get("(o)", &job);
249 INFO(SINK, "Waiting for job: " + std::string(job));
250 if (!watch.waitForJob(job))
251 throw runtime::Exception("Stopping unit: " + unit + " failed");
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 throw runtime::Exception("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::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 engine.reset(new INTERNAL_ENGINE(
385 source, INTERNAL_PATH,
386 ProgressBar([](int v) {
387 ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
388 std::to_string(v).c_str());
393 InternalEncryptionServer::~InternalEncryptionServer()
397 int InternalEncryptionServer::setMountPassword(const std::string& password)
399 const std::string& dev = engine->getSource();
401 // check if upgrade flag exists
402 if(UpgradeSupport::removeUpgradeFlag()) {
403 INFO("Upgrade flag detected.");
404 // try to load the master key
406 mountKey = UpgradeSupport::loadMasterKey(dev);
408 // encrypt the master key with given password
409 return keyServer.changePassword2(dev, mountKey, password);
410 } catch (const runtime::Exception&) {
411 INFO("Failed to load the master key stored during upgrade.");
415 return keyServer.get(dev, password, mountKey);
418 int InternalEncryptionServer::mount(const std::vector<unsigned char> &mk, unsigned int options)
420 if (mountKey.empty() && mk.empty()) {
421 ERROR(SINK, "You need to set master key first.");
422 return error::NoData;
425 BinaryData key = mk.empty() ? mountKey : mk;
428 if (getState() != State::Encrypted) {
429 INFO(SINK, "Cannot mount, SD partition's state incorrect.");
430 return error::NoSuchDevice;
433 if (engine->isMounted()) {
434 INFO(SINK, "Partition already mounted.");
438 INFO(SINK, "Mounting internal storage.");
440 engine->mount(key, getOptions());
442 server.notify("InternalEncryptionServer::mount");
444 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
445 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
446 } catch (runtime::Exception &e) {
447 ERROR(SINK, "Mount failed: " + std::string(e.what()));
448 return error::Unknown;
454 int InternalEncryptionServer::umount()
456 if (getState() != State::Encrypted) {
457 ERROR(SINK, "Cannot umount, partition's state incorrect.");
458 return error::NoSuchDevice;
461 if (!engine->isMounted()) {
462 INFO(SINK, "Partition already umounted.");
466 INFO(SINK, "Closing all processes using internal storage.");
468 stopKnownSystemdUnits();
469 stopDependedSystemdUnits();
470 INFO(SINK, "Umounting internal storage.");
471 unmountInternalStorage("/dev/mapper/userdata");
473 } catch (runtime::Exception &e) {
474 ERROR(SINK, "Umount failed: " + std::string(e.what()));
475 return error::Unknown;
481 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
483 if (getState() != State::Unencrypted) {
484 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
485 return error::NoSuchDevice;
488 BinaryData masterKey;
489 int ret = keyServer.get(engine->getSource(), password, masterKey);
490 if (ret != error::None)
493 auto encryptWorker = [masterKey, options, this]() {
495 showProgressUI("encrypt");
498 runtime::File file("/opt/etc/.odeprogress");
501 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
502 stopKnownSystemdUnits();
504 std::string source = engine->getSource();
505 auto mntPaths = findMountPointsByDevice(source);
507 if (!mntPaths.empty()) {
508 INFO(SINK, "Closing all processes using internal storage.");
509 stopDependedSystemdUnits();
511 INFO(SINK, "Unmounting internal storage.");
512 unmountInternalStorage(source);
515 INFO(SINK, "Encryption started.");
516 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
517 engine->encrypt(masterKey, options);
518 setOptions(options & getSupportedOptions());
520 INFO(SINK, "Encryption completed.");
521 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
522 server.notify("InternalEncryptionServer::mount");
526 INFO(SINK, "Syncing disk and rebooting.");
528 ::reboot(RB_AUTOBOOT);
529 } catch (runtime::Exception &e) {
530 ERROR(SINK, "Encryption failed: " + std::string(e.what()));
534 std::thread asyncWork(encryptWorker);
540 int InternalEncryptionServer::decrypt(const std::string& password)
542 if (getState() != State::Encrypted) {
543 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
544 return error::NoSuchDevice;
547 BinaryData masterKey;
548 int ret = keyServer.get(engine->getSource(), password, masterKey);
549 if (ret != error::None)
552 auto decryptWorker = [masterKey, this]() {
554 showProgressUI("decrypt");
557 runtime::File file("/opt/etc/.odeprogress");
560 if (engine->isMounted()) {
561 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
562 stopKnownSystemdUnits();
563 INFO(SINK, "Closing all processes using internal storage.");
564 stopDependedSystemdUnits();
566 INFO(SINK, "Umounting internal storage.");
567 unmountInternalStorage("/dev/mapper/userdata");
571 INFO(SINK, "Decryption started.");
572 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
573 engine->decrypt(masterKey, getOptions());
575 INFO(SINK, "Decryption complete.");
576 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
580 INFO(SINK, "Syncing disk and rebooting.");
582 ::reboot(RB_AUTOBOOT);
583 } catch (runtime::Exception &e) {
584 ERROR(SINK, "Decryption failed: " + std::string(e.what()));
588 std::thread asyncWork(decryptWorker);
594 int InternalEncryptionServer::recovery()
596 int state = getState();
598 if (state == State::Unencrypted)
599 return error::NoSuchDevice;
601 runtime::File file("/opt/.factoryreset");
606 dbus::Connection& systemDBus = dbus::Connection::getSystem();
607 systemDBus.methodcall("org.tizen.system.deviced",
608 "/Org/Tizen/System/DeviceD/Power",
609 "org.tizen.system.deviced.power",
611 -1, "()", "(si)", "reboot", 0);
612 } catch (runtime::Exception &e) {
613 ::reboot(RB_AUTOBOOT);
618 int InternalEncryptionServer::isPasswordInitialized()
620 return keyServer.isInitialized(engine->getSource());
623 int InternalEncryptionServer::initPassword(const std::string& password)
625 return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
628 int InternalEncryptionServer::cleanPassword(const std::string& password)
630 return keyServer.remove(engine->getSource(), password);
633 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
634 const std::string& newPassword)
636 return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
639 int InternalEncryptionServer::verifyPassword(const std::string& password)
641 return keyServer.verifyPassword(engine->getSource(), password);
644 int InternalEncryptionServer::getState()
646 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
648 throw runtime::Exception("Failed to get vconf value.");
651 std::string valueStr(value);
654 if (valueStr == "encrypted")
655 return State::Encrypted;
656 else if (valueStr == "unencrypted")
657 return State::Unencrypted;
658 else if (valueStr == "error_partially_encrypted" || valueStr == "error_partially_decrypted")
659 return State::Corrupted;
661 return State::Invalid;
664 unsigned int InternalEncryptionServer::getSupportedOptions()
666 return engine->getSupportedOptions();
669 std::string InternalEncryptionServer::getDevicePath() const
671 return engine->getSource();