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 dbus::VariantIterator iter;
171 std::vector<std::string> preprocessUnits;
172 std::set<std::string> unitsToStop;
174 auto stopUnit = [&systemDBus](const std::string &unit) {
175 JobWatch watch(systemDBus);
176 INFO(SINK, "Stopping unit: " + unit);
177 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 ERROR(SINK, "Stopping unit: " + unit + " failed");
187 } catch (runtime::Exception &e) {
188 ERROR(SINK, std::string(e.what()));
193 systemDBus.methodcall("org.freedesktop.systemd1",
194 "/org/freedesktop/systemd1",
195 "org.freedesktop.systemd1.Manager",
197 -1, "(a(ssssssouso))", "").get("(a(ssssssouso))", &iter);
198 } catch (runtime::Exception &e) {
199 INFO(SINK, "Get list of systemd unit : " + std::string(e.what()));
203 unsigned int dataUnit;
206 ret = iter.get("(ssssssouso)", dataStr, dataStr + 1, dataStr + 2,
207 dataStr + 3, dataStr + 4, dataStr + 5,
208 dataStr + 6, &dataUnit, dataStr + 7, dataStr + 8);
212 std::string unitName(dataStr[0]);
213 if (unitName == "security-manager.socket" ||
214 unitName == "connman.socket" ||
215 unitName == "msg-server.socket") {
216 preprocessUnits.insert(preprocessUnits.begin(), unitName);
217 } else if (unitName.compare(0, 5, "user@") == 0 ||
218 unitName == "tlm.service" ||
219 unitName == "resourced.service" ||
220 unitName == "security-manager.service") {
221 preprocessUnits.push_back(unitName);
225 for (auto unit : preprocessUnits) {
229 for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
231 char *unit = nullptr;
232 systemDBus.methodcall("org.freedesktop.systemd1",
233 "/org/freedesktop/systemd1",
234 "org.freedesktop.systemd1.Manager",
236 -1, "(o)", "(u)", (unsigned int)pid)
239 auto unescapedName = getDecodedPath(unit, "/org/freedesktop/systemd1/unit/");
240 unitsToStop.insert(unescapedName);
241 } catch (runtime::Exception &e) {
242 INFO(SINK, "Killing process: " + std::to_string(pid));
243 ::kill(pid, SIGKILL);
247 for (auto unit : unitsToStop) {
252 void showProgressUI(const std::string type)
254 dbus::Connection& systemDBus = dbus::Connection::getSystem();
255 std::string unit("ode-progress-ui@"+type+".service");
257 JobWatch watch(systemDBus);
258 INFO(SINK, "Start unit: " + unit);
260 const char* job = NULL;
261 systemDBus.methodcall("org.freedesktop.systemd1",
262 "/org/freedesktop/systemd1",
263 "org.freedesktop.systemd1.Manager",
265 -1, "(o)", "(ss)", unit.c_str(), "replace").get("(o)", &job);
267 INFO(SINK, "Waiting for job: " + std::string(job));
268 if (!watch.waitForJob(job))
269 ERROR(SINK, "Starting unit: " + unit + " failed");
272 unsigned int getOptions()
274 unsigned int result = 0;
278 ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
280 result |= InternalEncryption::Option::IncludeUnusedRegion;
286 void setOptions(unsigned int options)
290 if (options & InternalEncryption::Option::IncludeUnusedRegion) {
295 ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
298 void execAndWait(const std::string &path, std::vector<std::string> &args)
300 runtime::Process proc(path, args);
301 int ret = proc.execute();
303 ERROR(SINK, path + " failed for " + args.back());
305 ret = proc.waitForFinished();
306 if (ret < 0 || !WIFEXITED(ret) || WEXITSTATUS(ret) != 0)
307 ERROR(SINK, path + " failed for " + args.back());
310 bool isPartitionTerminated(const std::string &partition)
313 const std::string cmd("fuser -m " + partition + " | grep -o '[0-9]*'");
314 char *line = nullptr;
317 FILE *fp = ::popen(cmd.c_str(), "r");
319 ERROR(SINK, "Failed to get processes on partition");
323 if (::getline(&line, &len, fp) != -1)
332 void unmountInternalStorage(const std::string& source)
334 if (::umount2("/opt/usr", MNT_DETACH) == -1) {
335 if (errno != EBUSY && errno != EINVAL) {
336 throw runtime::Exception("umount() error : " + runtime::GetSystemErrorMessage());
342 static const char *fuserPath = "/usr/bin/fuser";
343 std::vector<std::string> args = {
344 fuserPath, "-m", "-k", "-s", "-SIGTERM", source,
346 execAndWait(fuserPath, args);
347 ::usleep((useconds_t)((unsigned int)(500)*1000));
349 args[4] = "-SIGKILL";
350 execAndWait(fuserPath, args);
351 ::usleep((useconds_t)((unsigned int)(200)*1000));
352 } while (!isPartitionTerminated(source));
357 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv,
362 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
363 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)(std::vector<unsigned char>, unsigned int));
364 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
365 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::isMounted)());
366 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
367 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
368 server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
369 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::recovery)());
370 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
371 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
372 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
373 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
374 server.expose(this, "", (int)(InternalEncryptionServer::getState)());
375 server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
376 server.expose(this, "", (std::string)(InternalEncryptionServer::getDevicePath)());
378 server.createNotification("InternalEncryptionServer::mount");
380 std::string source = findDevPath();
382 engine.reset(new INTERNAL_ENGINE(
383 source, INTERNAL_PATH,
384 ProgressBar([](int v) {
385 ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
386 std::to_string(v).c_str());
391 InternalEncryptionServer::~InternalEncryptionServer()
395 int InternalEncryptionServer::setMountPassword(const std::string& password)
397 const std::string& dev = engine->getSource();
399 // check if upgrade flag exists
400 if(UpgradeSupport::removeUpgradeFlag()) {
401 INFO("Upgrade flag detected.");
402 // try to load the master key
404 mountKey = UpgradeSupport::loadMasterKey(dev);
406 // encrypt the master key with given password
407 return keyServer.changePassword2(dev, mountKey, password);
408 } catch (const runtime::Exception&) {
409 INFO("Failed to load the master key stored during upgrade.");
413 return keyServer.get(dev, password, mountKey);
416 int InternalEncryptionServer::mount(const std::vector<unsigned char> &mk, unsigned int options)
418 if (mountKey.empty() && mk.empty()) {
419 ERROR(SINK, "You need to set master key first.");
420 return error::NoData;
423 BinaryData key = mk.empty() ? mountKey : mk;
426 if (getState() != State::Encrypted) {
427 INFO(SINK, "Cannot mount, SD partition's state incorrect.");
428 return error::NoSuchDevice;
431 if (engine->isMounted()) {
432 INFO(SINK, "Partition already mounted.");
436 INFO(SINK, "Mounting internal storage.");
438 engine->mount(key, getOptions());
440 server.notify("InternalEncryptionServer::mount");
442 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
443 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
444 } catch (runtime::Exception &e) {
445 ERROR(SINK, "Mount failed: " + std::string(e.what()));
446 return error::Unknown;
452 int InternalEncryptionServer::isMounted()
456 ret = engine->isMounted() ? 1 : 0;
457 } catch (runtime::Exception &e) {
458 ERROR(SINK, "Failed to access the mount flag");
459 return error::Unknown;
464 int InternalEncryptionServer::umount()
466 if (getState() != State::Encrypted) {
467 ERROR(SINK, "Cannot umount, partition's state incorrect.");
468 return error::NoSuchDevice;
471 if (!engine->isMounted()) {
472 INFO(SINK, "Partition already umounted.");
476 INFO(SINK, "Closing all processes using internal storage.");
479 INFO(SINK, "Umounting internal storage.");
480 unmountInternalStorage("/dev/mapper/userdata");
482 } catch (runtime::Exception &e) {
483 ERROR(SINK, "Umount failed: " + std::string(e.what()));
484 return error::Unknown;
490 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
492 if (getState() != State::Unencrypted) {
493 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
494 return error::NoSuchDevice;
497 BinaryData masterKey;
498 int ret = keyServer.get(engine->getSource(), password, masterKey);
499 if (ret != error::None)
502 auto encryptWorker = [masterKey, options, this]() {
504 showProgressUI("encrypt");
507 runtime::File file("/opt/etc/.odeprogress");
510 std::string source = engine->getSource();
511 auto mntPaths = findMountPointsByDevice(source);
513 if (!mntPaths.empty()) {
514 INFO(SINK, "Closing all processes using internal storage.");
517 INFO(SINK, "Unmounting internal storage.");
518 unmountInternalStorage(source);
521 INFO(SINK, "Encryption started.");
522 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
523 engine->encrypt(masterKey, options);
524 setOptions(options & getSupportedOptions());
526 INFO(SINK, "Encryption completed.");
527 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
528 server.notify("InternalEncryptionServer::mount");
532 INFO(SINK, "Syncing disk and rebooting.");
534 ::reboot(RB_AUTOBOOT);
535 } catch (runtime::Exception &e) {
536 ERROR(SINK, "Encryption failed: " + std::string(e.what()));
540 std::thread asyncWork(encryptWorker);
546 int InternalEncryptionServer::decrypt(const std::string& password)
548 if (getState() != State::Encrypted) {
549 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
550 return error::NoSuchDevice;
553 BinaryData masterKey;
554 int ret = keyServer.get(engine->getSource(), password, masterKey);
555 if (ret != error::None)
558 auto decryptWorker = [masterKey, this]() {
560 showProgressUI("decrypt");
563 runtime::File file("/opt/etc/.odeprogress");
566 if (engine->isMounted()) {
567 INFO(SINK, "Closing all processes using internal storage.");
570 INFO(SINK, "Umounting internal storage.");
571 unmountInternalStorage("/dev/mapper/userdata");
575 INFO(SINK, "Decryption started.");
576 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
577 engine->decrypt(masterKey, getOptions());
579 INFO(SINK, "Decryption complete.");
580 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
584 INFO(SINK, "Syncing disk and rebooting.");
586 ::reboot(RB_AUTOBOOT);
587 } catch (runtime::Exception &e) {
588 ERROR(SINK, "Decryption failed: " + std::string(e.what()));
592 std::thread asyncWork(decryptWorker);
598 int InternalEncryptionServer::recovery()
600 int state = getState();
602 if (state == State::Unencrypted)
603 return error::NoSuchDevice;
605 runtime::File file("/opt/.factoryreset");
610 dbus::Connection& systemDBus = dbus::Connection::getSystem();
611 systemDBus.methodcall("org.tizen.system.deviced",
612 "/Org/Tizen/System/DeviceD/Power",
613 "org.tizen.system.deviced.power",
615 -1, "()", "(si)", "reboot", 0);
616 } catch (runtime::Exception &e) {
617 ::reboot(RB_AUTOBOOT);
622 int InternalEncryptionServer::isPasswordInitialized()
624 return keyServer.isInitialized(engine->getSource());
627 int InternalEncryptionServer::initPassword(const std::string& password)
629 return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
632 int InternalEncryptionServer::cleanPassword(const std::string& password)
634 return keyServer.remove(engine->getSource(), password);
637 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
638 const std::string& newPassword)
640 return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
643 int InternalEncryptionServer::verifyPassword(const std::string& password)
645 return keyServer.verifyPassword(engine->getSource(), password);
648 int InternalEncryptionServer::getState()
650 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
652 throw runtime::Exception("Failed to get vconf value.");
655 std::string valueStr(value);
658 if (valueStr == "encrypted")
659 return State::Encrypted;
660 else if (valueStr == "unencrypted")
661 return State::Unencrypted;
662 else if (valueStr == "error_partially_encrypted" || valueStr == "error_partially_decrypted")
663 return State::Corrupted;
665 return State::Invalid;
668 unsigned int InternalEncryptionServer::getSupportedOptions()
670 return engine->getSupportedOptions();
673 std::string InternalEncryptionServer::getDevicePath() const
675 return engine->getSource();