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";
57 // watches systemd jobs
60 explicit JobWatch(dbus::Connection& systemDBus);
63 bool waitForJob(const std::string& job);
66 void jobRemoved(const dbus::Variant& parameters);
70 const std::string& job,
71 const std::string& unit,
72 const std::string& result) : id(id), job(job), unit(unit), result(result) {}
79 dbus::Connection::SubscriptionId id;
80 dbus::Connection& systemDBus;
81 std::list<Job> removedJobs;
83 std::condition_variable jobsCv;
86 JobWatch::JobWatch(dbus::Connection& systemDBus) : systemDBus(systemDBus) {
87 auto callback = [this](dbus::Variant parameters) {
88 this->jobRemoved(parameters);
91 id = systemDBus.subscribeSignal("",
92 "/org/freedesktop/systemd1",
93 "org.freedesktop.systemd1.Manager",
98 JobWatch::~JobWatch() {
99 systemDBus.unsubscribeSignal(id);
102 bool JobWatch::waitForJob(const std::string& job) {
104 std::unique_lock<std::mutex> lock(jobsMutex);
106 auto sec = std::chrono::seconds(1);
107 jobsCv.wait_for(lock, 5*sec, [this, &timeout]{
108 if (!removedJobs.empty()) {
115 INFO(SINK, "job: " + job + ", result: time out");
119 while(!removedJobs.empty()) {
120 bool match = (removedJobs.front().job == job);
121 bool done = (removedJobs.front().result == "done");
122 removedJobs.pop_front();
129 void JobWatch::jobRemoved(const dbus::Variant& parameters)
135 parameters.get("(uoss)", &id, &job, &unit, &result);
136 INFO(SINK, "id:" + std::to_string(id) + " job:" + job + " unit:" + unit + " result:" + result);
139 std::lock_guard<std::mutex> guard(jobsMutex);
140 removedJobs.emplace_back(id, job, unit, result);
145 std::string getDecodedPath(const std::string &path, const std::string &prefix)
147 std::string ret = path;
150 pos = ret.find(prefix);
151 if (pos != std::string::npos)
152 ret = ret.substr(prefix.size(), ret.size());
155 while ((pos = ret.find("_", pos)) != std::string::npos) {
156 int a = std::stoi(std::string(1, ret.at(pos+1)), nullptr, 16);
157 int b = std::stoi(std::string(1, ret.at(pos+2)), nullptr, 16);
159 ret.replace(pos, 3, "_");
161 ret.replace(pos, 3, std::string(1, ((a << 4) | b)));
167 void stopSystemdUnits()
169 dbus::Connection& systemDBus = dbus::Connection::getSystem();
170 std::set<std::string> preprocessUnits;
171 std::set<std::string> unitsToStop;
173 for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
175 char *unit = nullptr;
176 systemDBus.methodcall("org.freedesktop.systemd1",
177 "/org/freedesktop/systemd1",
178 "org.freedesktop.systemd1.Manager",
180 -1, "(o)", "(u)", (unsigned int)pid)
183 auto unescapedName = getDecodedPath(unit, "/org/freedesktop/systemd1/unit/");
184 if (unescapedName.compare(0, 5, "user@") == 0)
185 preprocessUnits.insert(unescapedName);
187 unitsToStop.insert(unescapedName);
188 } catch (runtime::Exception &e) {
189 INFO(SINK, "Killing process: " + std::to_string(pid));
190 ::kill(pid, SIGKILL);
194 JobWatch watch(systemDBus);
196 auto stopUnit = [&watch, &systemDBus](const std::string &unit) {
197 INFO(SINK, "Stopping unit: " + unit);
198 const char* job = NULL;
199 systemDBus.methodcall("org.freedesktop.systemd1",
200 "/org/freedesktop/systemd1",
201 "org.freedesktop.systemd1.Manager",
203 -1, "(o)", "(ss)", unit.c_str(), "flush").get("(o)", &job);
204 INFO(SINK, "Waiting for job: " + std::string(job));
205 if (!watch.waitForJob(job))
206 ERROR(SINK, "Stopping unit: " + unit + " failed");
209 for (const std::string &unit : preprocessUnits) {
213 for (const std::string &unit : unitsToStop) {
218 void showProgressUI(const std::string type)
220 dbus::Connection& systemDBus = dbus::Connection::getSystem();
221 std::string unit("ode-progress-ui@"+type+".service");
223 JobWatch watch(systemDBus);
224 INFO(SINK, "Start unit: " + unit);
226 const char* job = NULL;
227 systemDBus.methodcall("org.freedesktop.systemd1",
228 "/org/freedesktop/systemd1",
229 "org.freedesktop.systemd1.Manager",
231 -1, "(o)", "(ss)", unit.c_str(), "replace").get("(o)", &job);
233 INFO(SINK, "Waiting for job: " + std::string(job));
234 if (!watch.waitForJob(job))
235 ERROR(SINK, "Starting unit: " + unit + " failed");
238 unsigned int getOptions()
240 unsigned int result = 0;
244 ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
246 result |= InternalEncryption::Option::IncludeUnusedRegion;
252 void setOptions(unsigned int options)
256 if (options & InternalEncryption::Option::IncludeUnusedRegion) {
261 ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
264 void execAndWait(const std::string &path, std::vector<std::string> &args)
266 runtime::Process proc(path, args);
267 int ret = proc.execute();
269 ERROR(SINK, path + " failed for " + args.back());
271 ret = proc.waitForFinished();
272 if (ret < 0 || !WIFEXITED(ret) || WEXITSTATUS(ret) != 0)
273 ERROR(SINK, path + " failed for " + args.back());
276 bool isPartitionTerminated(const std::string &partition)
279 const std::string cmd("fuser -m " + partition + " | grep -o '[0-9]*'");
280 char *line = nullptr;
283 FILE *fp = ::popen(cmd.c_str(), "r");
285 ERROR(SINK, "Failed to get processes on partition");
289 if (::getline(&line, &len, fp) != -1)
298 void unmountInternalStorage(const std::string& source)
300 if (::umount2("/opt/usr", MNT_DETACH) == -1) {
301 if (errno != EBUSY && errno != EINVAL) {
302 throw runtime::Exception("umount() error : " + runtime::GetSystemErrorMessage());
308 static const char *fuserPath = "/usr/bin/fuser";
309 std::vector<std::string> args = {
310 fuserPath, "-m", "-k", "-s", "-SIGTERM", source,
312 execAndWait(fuserPath, args);
313 ::usleep((useconds_t)((unsigned int)(500)*1000));
315 args[4] = "-SIGKILL";
316 execAndWait(fuserPath, args);
317 ::usleep((useconds_t)((unsigned int)(200)*1000));
318 } while (!isPartitionTerminated(source));
323 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv,
328 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
329 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)(std::vector<unsigned char>, unsigned int));
330 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
331 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::isMounted)());
332 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
333 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
334 server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
335 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::recovery)());
336 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
337 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
338 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
339 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
340 server.expose(this, "", (int)(InternalEncryptionServer::getState)());
341 server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
342 server.expose(this, "", (std::string)(InternalEncryptionServer::getDevicePath)());
344 server.createNotification("InternalEncryptionServer::mount");
346 std::string source = findDevPath();
348 engine.reset(new INTERNAL_ENGINE(
349 source, INTERNAL_PATH,
350 ProgressBar([](int v) {
351 ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
352 std::to_string(v).c_str());
357 InternalEncryptionServer::~InternalEncryptionServer()
361 int InternalEncryptionServer::setMountPassword(const std::string& password)
363 const std::string& dev = engine->getSource();
365 // check if upgrade flag exists
366 if(UpgradeSupport::removeUpgradeFlag()) {
367 INFO("Upgrade flag detected.");
368 // try to load the master key
370 mountKey = UpgradeSupport::loadMasterKey(dev);
372 // encrypt the master key with given password
373 return keyServer.changePassword2(dev, mountKey, password);
374 } catch (const runtime::Exception&) {
375 INFO("Failed to load the master key stored during upgrade.");
379 return keyServer.get(dev, password, mountKey);
382 int InternalEncryptionServer::mount(const std::vector<unsigned char> &mk, unsigned int options)
384 if (mountKey.empty() && mk.empty()) {
385 ERROR(SINK, "You need to set master key first.");
386 return error::NoData;
389 BinaryData key = mk.empty() ? mountKey : mk;
392 if (getState() != State::Encrypted) {
393 INFO(SINK, "Cannot mount, SD partition's state incorrect.");
394 return error::NoSuchDevice;
397 if (engine->isMounted()) {
398 INFO(SINK, "Partition already mounted.");
402 INFO(SINK, "Mounting internal storage.");
404 engine->mount(key, getOptions());
406 server.notify("InternalEncryptionServer::mount");
408 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
409 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
410 } catch (runtime::Exception &e) {
411 ERROR(SINK, "Mount failed: " + std::string(e.what()));
412 return error::Unknown;
418 int InternalEncryptionServer::isMounted()
422 ret = engine->isMounted() ? 1 : 0;
423 } catch (runtime::Exception &e) {
424 ERROR(SINK, "Failed to access the mount flag");
425 return error::Unknown;
430 int InternalEncryptionServer::umount()
432 if (getState() != State::Encrypted) {
433 ERROR(SINK, "Cannot umount, partition's state incorrect.");
434 return error::NoSuchDevice;
437 if (!engine->isMounted()) {
438 INFO(SINK, "Partition already umounted.");
442 INFO(SINK, "Closing all processes using internal storage.");
445 INFO(SINK, "Umounting internal storage.");
446 unmountInternalStorage("/dev/mapper/userdata");
448 } catch (runtime::Exception &e) {
449 ERROR(SINK, "Umount failed: " + std::string(e.what()));
450 return error::Unknown;
456 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
458 if (getState() != State::Unencrypted) {
459 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
460 return error::NoSuchDevice;
463 BinaryData masterKey;
464 int ret = keyServer.get(engine->getSource(), password, masterKey);
465 if (ret != error::None)
468 auto encryptWorker = [masterKey, options, this]() {
470 showProgressUI("encrypt");
473 runtime::File file("/opt/etc/.odeprogress");
476 std::string source = engine->getSource();
477 auto mntPaths = findMountPointsByDevice(source);
479 if (!mntPaths.empty()) {
480 INFO(SINK, "Closing all processes using internal storage.");
483 INFO(SINK, "Unmounting internal storage.");
484 unmountInternalStorage(source);
487 INFO(SINK, "Encryption started.");
488 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
489 engine->encrypt(masterKey, options);
490 setOptions(options & getSupportedOptions());
492 INFO(SINK, "Encryption completed.");
493 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
494 server.notify("InternalEncryptionServer::mount");
498 INFO(SINK, "Syncing disk and rebooting.");
500 ::reboot(RB_AUTOBOOT);
501 } catch (runtime::Exception &e) {
502 ERROR(SINK, "Encryption failed: " + std::string(e.what()));
506 std::thread asyncWork(encryptWorker);
512 int InternalEncryptionServer::decrypt(const std::string& password)
514 if (getState() != State::Encrypted) {
515 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
516 return error::NoSuchDevice;
519 BinaryData masterKey;
520 int ret = keyServer.get(engine->getSource(), password, masterKey);
521 if (ret != error::None)
524 auto decryptWorker = [masterKey, this]() {
526 showProgressUI("decrypt");
529 runtime::File file("/opt/etc/.odeprogress");
532 if (engine->isMounted()) {
533 INFO(SINK, "Closing all processes using internal storage.");
536 INFO(SINK, "Umounting internal storage.");
537 unmountInternalStorage("/dev/mapper/userdata");
541 INFO(SINK, "Decryption started.");
542 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
543 engine->decrypt(masterKey, getOptions());
545 INFO(SINK, "Decryption complete.");
546 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
550 INFO(SINK, "Syncing disk and rebooting.");
552 ::reboot(RB_AUTOBOOT);
553 } catch (runtime::Exception &e) {
554 ERROR(SINK, "Decryption failed: " + std::string(e.what()));
558 std::thread asyncWork(decryptWorker);
564 int InternalEncryptionServer::recovery()
566 int state = getState();
568 if (state == State::Unencrypted)
569 return error::NoSuchDevice;
571 runtime::File file("/opt/.factoryreset");
576 dbus::Connection& systemDBus = dbus::Connection::getSystem();
577 systemDBus.methodcall("org.tizen.system.deviced",
578 "/Org/Tizen/System/DeviceD/Power",
579 "org.tizen.system.deviced.power",
581 -1, "()", "(si)", "reboot", 0);
582 } catch (runtime::Exception &e) {
583 ::reboot(RB_AUTOBOOT);
588 int InternalEncryptionServer::isPasswordInitialized()
590 return keyServer.isInitialized(engine->getSource());
593 int InternalEncryptionServer::initPassword(const std::string& password)
595 return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
598 int InternalEncryptionServer::cleanPassword(const std::string& password)
600 return keyServer.remove(engine->getSource(), password);
603 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
604 const std::string& newPassword)
606 return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
609 int InternalEncryptionServer::verifyPassword(const std::string& password)
611 return keyServer.verifyPassword(engine->getSource(), password);
614 int InternalEncryptionServer::getState()
616 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
618 throw runtime::Exception("Failed to get vconf value.");
621 std::string valueStr(value);
624 if (valueStr == "encrypted")
625 return State::Encrypted;
626 else if (valueStr == "unencrypted")
627 return State::Unencrypted;
628 else if (valueStr == "error_partially_encrypted" || valueStr == "error_partially_decrypted")
629 return State::Corrupted;
631 return State::Invalid;
634 unsigned int InternalEncryptionServer::getSupportedOptions()
636 return engine->getSupportedOptions();
639 std::string InternalEncryptionServer::getDevicePath() const
641 return engine->getSource();