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::isMounted)());
369 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
370 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
371 server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
372 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::recovery)());
373 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
374 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
375 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
376 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
377 server.expose(this, "", (int)(InternalEncryptionServer::getState)());
378 server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
379 server.expose(this, "", (std::string)(InternalEncryptionServer::getDevicePath)());
381 server.createNotification("InternalEncryptionServer::mount");
383 std::string source = findDevPath();
385 engine.reset(new INTERNAL_ENGINE(
386 source, INTERNAL_PATH,
387 ProgressBar([](int v) {
388 ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
389 std::to_string(v).c_str());
394 InternalEncryptionServer::~InternalEncryptionServer()
398 int InternalEncryptionServer::setMountPassword(const std::string& password)
400 const std::string& dev = engine->getSource();
402 // check if upgrade flag exists
403 if(UpgradeSupport::removeUpgradeFlag()) {
404 INFO("Upgrade flag detected.");
405 // try to load the master key
407 mountKey = UpgradeSupport::loadMasterKey(dev);
409 // encrypt the master key with given password
410 return keyServer.changePassword2(dev, mountKey, password);
411 } catch (const runtime::Exception&) {
412 INFO("Failed to load the master key stored during upgrade.");
416 return keyServer.get(dev, password, mountKey);
419 int InternalEncryptionServer::mount(const std::vector<unsigned char> &mk, unsigned int options)
421 if (mountKey.empty() && mk.empty()) {
422 ERROR(SINK, "You need to set master key first.");
423 return error::NoData;
426 BinaryData key = mk.empty() ? mountKey : mk;
429 if (getState() != State::Encrypted) {
430 INFO(SINK, "Cannot mount, SD partition's state incorrect.");
431 return error::NoSuchDevice;
434 if (engine->isMounted()) {
435 INFO(SINK, "Partition already mounted.");
439 INFO(SINK, "Mounting internal storage.");
441 engine->mount(key, getOptions());
443 server.notify("InternalEncryptionServer::mount");
445 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
446 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
447 } catch (runtime::Exception &e) {
448 ERROR(SINK, "Mount failed: " + std::string(e.what()));
449 return error::Unknown;
455 int InternalEncryptionServer::isMounted()
459 ret = engine->isMounted() ? 1 : 0;
460 } catch (runtime::Exception &e) {
461 ERROR(SINK, "Failed to access the mount flag");
462 return error::Unknown;
467 int InternalEncryptionServer::umount()
469 if (getState() != State::Encrypted) {
470 ERROR(SINK, "Cannot umount, partition's state incorrect.");
471 return error::NoSuchDevice;
474 if (!engine->isMounted()) {
475 INFO(SINK, "Partition already umounted.");
479 INFO(SINK, "Closing all processes using internal storage.");
481 stopKnownSystemdUnits();
482 stopDependedSystemdUnits();
483 INFO(SINK, "Umounting internal storage.");
484 unmountInternalStorage("/dev/mapper/userdata");
486 } catch (runtime::Exception &e) {
487 ERROR(SINK, "Umount failed: " + std::string(e.what()));
488 return error::Unknown;
494 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
496 if (getState() != State::Unencrypted) {
497 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
498 return error::NoSuchDevice;
501 BinaryData masterKey;
502 int ret = keyServer.get(engine->getSource(), password, masterKey);
503 if (ret != error::None)
506 auto encryptWorker = [masterKey, options, this]() {
508 showProgressUI("encrypt");
511 runtime::File file("/opt/etc/.odeprogress");
514 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
515 stopKnownSystemdUnits();
517 std::string source = engine->getSource();
518 auto mntPaths = findMountPointsByDevice(source);
520 if (!mntPaths.empty()) {
521 INFO(SINK, "Closing all processes using internal storage.");
522 stopDependedSystemdUnits();
524 INFO(SINK, "Unmounting internal storage.");
525 unmountInternalStorage(source);
528 INFO(SINK, "Encryption started.");
529 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
530 engine->encrypt(masterKey, options);
531 setOptions(options & getSupportedOptions());
533 INFO(SINK, "Encryption completed.");
534 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
535 server.notify("InternalEncryptionServer::mount");
539 INFO(SINK, "Syncing disk and rebooting.");
541 ::reboot(RB_AUTOBOOT);
542 } catch (runtime::Exception &e) {
543 ERROR(SINK, "Encryption failed: " + std::string(e.what()));
547 std::thread asyncWork(encryptWorker);
553 int InternalEncryptionServer::decrypt(const std::string& password)
555 if (getState() != State::Encrypted) {
556 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
557 return error::NoSuchDevice;
560 BinaryData masterKey;
561 int ret = keyServer.get(engine->getSource(), password, masterKey);
562 if (ret != error::None)
565 auto decryptWorker = [masterKey, this]() {
567 showProgressUI("decrypt");
570 runtime::File file("/opt/etc/.odeprogress");
573 if (engine->isMounted()) {
574 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
575 stopKnownSystemdUnits();
576 INFO(SINK, "Closing all processes using internal storage.");
577 stopDependedSystemdUnits();
579 INFO(SINK, "Umounting internal storage.");
580 unmountInternalStorage("/dev/mapper/userdata");
584 INFO(SINK, "Decryption started.");
585 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
586 engine->decrypt(masterKey, getOptions());
588 INFO(SINK, "Decryption complete.");
589 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
593 INFO(SINK, "Syncing disk and rebooting.");
595 ::reboot(RB_AUTOBOOT);
596 } catch (runtime::Exception &e) {
597 ERROR(SINK, "Decryption failed: " + std::string(e.what()));
601 std::thread asyncWork(decryptWorker);
607 int InternalEncryptionServer::recovery()
609 int state = getState();
611 if (state == State::Unencrypted)
612 return error::NoSuchDevice;
614 runtime::File file("/opt/.factoryreset");
619 dbus::Connection& systemDBus = dbus::Connection::getSystem();
620 systemDBus.methodcall("org.tizen.system.deviced",
621 "/Org/Tizen/System/DeviceD/Power",
622 "org.tizen.system.deviced.power",
624 -1, "()", "(si)", "reboot", 0);
625 } catch (runtime::Exception &e) {
626 ::reboot(RB_AUTOBOOT);
631 int InternalEncryptionServer::isPasswordInitialized()
633 return keyServer.isInitialized(engine->getSource());
636 int InternalEncryptionServer::initPassword(const std::string& password)
638 return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
641 int InternalEncryptionServer::cleanPassword(const std::string& password)
643 return keyServer.remove(engine->getSource(), password);
646 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
647 const std::string& newPassword)
649 return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
652 int InternalEncryptionServer::verifyPassword(const std::string& password)
654 return keyServer.verifyPassword(engine->getSource(), password);
657 int InternalEncryptionServer::getState()
659 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
661 throw runtime::Exception("Failed to get vconf value.");
664 std::string valueStr(value);
667 if (valueStr == "encrypted")
668 return State::Encrypted;
669 else if (valueStr == "unencrypted")
670 return State::Unencrypted;
671 else if (valueStr == "error_partially_encrypted" || valueStr == "error_partially_decrypted")
672 return State::Corrupted;
674 return State::Invalid;
677 unsigned int InternalEncryptionServer::getSupportedOptions()
679 return engine->getSupportedOptions();
682 std::string InternalEncryptionServer::getDevicePath() const
684 return engine->getSource();