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 std::string getDecodedPath(const std::string &path, const std::string &prefix)
138 std::string ret = path;
141 pos = ret.find(prefix);
142 if (pos != std::string::npos)
143 ret = ret.substr(prefix.size(), ret.size());
146 while ((pos = ret.find("_", pos)) != std::string::npos) {
147 int a = std::stoi(std::string(1, ret.at(pos+1)), nullptr, 16);
148 int b = std::stoi(std::string(1, ret.at(pos+2)), nullptr, 16);
150 ret.replace(pos, 3, "_");
152 ret.replace(pos, 3, std::string(1, ((a << 4) | b)));
158 void stopSystemdUnits()
160 dbus::Connection& systemDBus = dbus::Connection::getSystem();
161 std::set<std::string> preprocessUnits;
162 std::set<std::string> unitsToStop;
164 for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
166 char *unit = nullptr;
167 systemDBus.methodcall("org.freedesktop.systemd1",
168 "/org/freedesktop/systemd1",
169 "org.freedesktop.systemd1.Manager",
171 -1, "(o)", "(u)", (unsigned int)pid)
174 auto unescapedName = getDecodedPath(unit, "/org/freedesktop/systemd1/unit/");
175 if (unescapedName.compare(0, 5, "user@") == 0)
176 preprocessUnits.insert(unescapedName);
178 unitsToStop.insert(unescapedName);
179 } catch (runtime::Exception &e) {
180 INFO(SINK, "Killing process: " + std::to_string(pid));
181 ::kill(pid, SIGKILL);
185 for (auto unit : blackListSystemdUnits) {
186 unitsToStop.erase(unitsToStop.find(unit));
189 auto stopUnit = [&systemDBus](const std::string &unit) {
190 INFO(SINK, "Stopping unit: " + unit);
191 JobWatch watch(systemDBus);
192 const char* job = NULL;
193 systemDBus.methodcall("org.freedesktop.systemd1",
194 "/org/freedesktop/systemd1",
195 "org.freedesktop.systemd1.Manager",
197 -1, "(o)", "(ss)", unit.c_str(), "flush").get("(o)", &job);
198 INFO(SINK, "Waiting for job: " + std::string(job));
199 if (!watch.waitForJob(job))
200 ERROR(SINK, "Stopping unit: " + unit + " failed");
203 for (const std::string &unit : preprocessUnits) {
207 for (const std::string &unit : unitsToStop) {
212 void showProgressUI(const std::string type)
214 dbus::Connection& systemDBus = dbus::Connection::getSystem();
215 std::string unit("ode-progress-ui@"+type+".service");
217 JobWatch watch(systemDBus);
218 INFO(SINK, "Start unit: " + unit);
220 const char* job = NULL;
221 systemDBus.methodcall("org.freedesktop.systemd1",
222 "/org/freedesktop/systemd1",
223 "org.freedesktop.systemd1.Manager",
225 -1, "(o)", "(ss)", unit.c_str(), "replace").get("(o)", &job);
227 INFO(SINK, "Waiting for job: " + std::string(job));
228 if (!watch.waitForJob(job))
229 ERROR(SINK, "Starting unit: " + unit + " failed");
232 unsigned int getOptions()
234 unsigned int result = 0;
238 ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
240 result |= InternalEncryption::Option::IncludeUnusedRegion;
246 void setOptions(unsigned int options)
250 if (options & InternalEncryption::Option::IncludeUnusedRegion) {
255 ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
258 void execAndWait(const std::string &path, std::vector<std::string> &args)
260 runtime::Process proc(path, args);
261 int ret = proc.execute();
263 ERROR(SINK, path + " failed for " + args.back());
265 ret = proc.waitForFinished();
266 if (ret < 0 || !WIFEXITED(ret) || WEXITSTATUS(ret) != 0)
267 ERROR(SINK, path + " failed for " + args.back());
270 bool isPartitionTerminated(const std::string &partition)
273 const std::string cmd("fuser -m " + partition + " | grep -o '[0-9]*'");
274 char *line = nullptr;
277 FILE *fp = ::popen(cmd.c_str(), "r");
279 ERROR(SINK, "Failed to get processes on partition");
283 if (::getline(&line, &len, fp) != -1)
292 void unmountInternalStorage(const std::string& source)
294 if (::umount2("/opt/usr", MNT_DETACH) == -1) {
295 if (errno != EBUSY && errno != EINVAL) {
296 throw runtime::Exception("umount() error : " + runtime::GetSystemErrorMessage());
302 static const char *fuserPath = "/usr/bin/fuser";
303 std::vector<std::string> args = {
304 fuserPath, "-m", "-k", "-s", "-SIGTERM", source,
306 execAndWait(fuserPath, args);
307 ::usleep((useconds_t)((unsigned int)(500)*1000));
309 args[4] = "-SIGKILL";
310 execAndWait(fuserPath, args);
311 ::usleep((useconds_t)((unsigned int)(200)*1000));
312 } while (!isPartitionTerminated(source));
317 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv,
322 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
323 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)(std::vector<unsigned char>, unsigned int));
324 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
325 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::isMounted)());
326 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
327 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
328 server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
329 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::recovery)());
330 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
331 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
332 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
333 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
334 server.expose(this, "", (int)(InternalEncryptionServer::getState)());
335 server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
336 server.expose(this, "", (std::string)(InternalEncryptionServer::getDevicePath)());
338 server.createNotification("InternalEncryptionServer::mount");
340 std::string source = findDevPath();
342 engine.reset(new INTERNAL_ENGINE(
343 source, INTERNAL_PATH,
344 ProgressBar([](int v) {
345 ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
346 std::to_string(v).c_str());
351 InternalEncryptionServer::~InternalEncryptionServer()
355 int InternalEncryptionServer::setMountPassword(const std::string& password)
357 const std::string& dev = engine->getSource();
359 // check if upgrade flag exists
360 if(UpgradeSupport::removeUpgradeFlag()) {
361 INFO("Upgrade flag detected.");
362 // try to load the master key
364 mountKey = UpgradeSupport::loadMasterKey(dev);
366 // encrypt the master key with given password
367 return keyServer.changePassword2(dev, mountKey, password);
368 } catch (const runtime::Exception&) {
369 INFO("Failed to load the master key stored during upgrade.");
373 return keyServer.get(dev, password, mountKey);
376 int InternalEncryptionServer::mount(const std::vector<unsigned char> &mk, unsigned int options)
378 if (mountKey.empty() && mk.empty()) {
379 ERROR(SINK, "You need to set master key first.");
380 return error::NoData;
383 BinaryData key = mk.empty() ? mountKey : mk;
386 if (getState() != State::Encrypted) {
387 INFO(SINK, "Cannot mount, SD partition's state incorrect.");
388 return error::NoSuchDevice;
391 if (engine->isMounted()) {
392 INFO(SINK, "Partition already mounted.");
396 INFO(SINK, "Mounting internal storage.");
398 engine->mount(key, getOptions());
400 server.notify("InternalEncryptionServer::mount");
402 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
403 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
404 } catch (runtime::Exception &e) {
405 ERROR(SINK, "Mount failed: " + std::string(e.what()));
406 return error::Unknown;
412 int InternalEncryptionServer::isMounted()
416 ret = engine->isMounted() ? 1 : 0;
417 } catch (runtime::Exception &e) {
418 ERROR(SINK, "Failed to access the mount flag");
419 return error::Unknown;
424 int InternalEncryptionServer::umount()
426 if (getState() != State::Encrypted) {
427 ERROR(SINK, "Cannot umount, partition's state incorrect.");
428 return error::NoSuchDevice;
431 if (!engine->isMounted()) {
432 INFO(SINK, "Partition already umounted.");
436 INFO(SINK, "Closing all processes using internal storage.");
439 INFO(SINK, "Umounting internal storage.");
440 unmountInternalStorage("/dev/mapper/userdata");
442 } catch (runtime::Exception &e) {
443 ERROR(SINK, "Umount failed: " + std::string(e.what()));
444 return error::Unknown;
450 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
452 if (getState() != State::Unencrypted) {
453 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
454 return error::NoSuchDevice;
457 BinaryData masterKey;
458 int ret = keyServer.get(engine->getSource(), password, masterKey);
459 if (ret != error::None)
462 auto encryptWorker = [masterKey, options, this]() {
464 showProgressUI("encrypt");
467 runtime::File file("/opt/etc/.odeprogress");
470 std::string source = engine->getSource();
471 auto mntPaths = findMountPointsByDevice(source);
473 if (!mntPaths.empty()) {
474 INFO(SINK, "Closing all processes using internal storage.");
477 INFO(SINK, "Unmounting internal storage.");
478 unmountInternalStorage(source);
481 INFO(SINK, "Encryption started.");
482 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
483 engine->encrypt(masterKey, options);
484 setOptions(options & getSupportedOptions());
486 INFO(SINK, "Encryption completed.");
487 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
488 server.notify("InternalEncryptionServer::mount");
492 INFO(SINK, "Syncing disk and rebooting.");
494 ::reboot(RB_AUTOBOOT);
495 } catch (runtime::Exception &e) {
496 ERROR(SINK, "Encryption failed: " + std::string(e.what()));
500 std::thread asyncWork(encryptWorker);
506 int InternalEncryptionServer::decrypt(const std::string& password)
508 if (getState() != State::Encrypted) {
509 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
510 return error::NoSuchDevice;
513 BinaryData masterKey;
514 int ret = keyServer.get(engine->getSource(), password, masterKey);
515 if (ret != error::None)
518 auto decryptWorker = [masterKey, this]() {
520 showProgressUI("decrypt");
523 runtime::File file("/opt/etc/.odeprogress");
526 if (engine->isMounted()) {
527 INFO(SINK, "Closing all processes using internal storage.");
530 INFO(SINK, "Umounting internal storage.");
531 unmountInternalStorage("/dev/mapper/userdata");
535 INFO(SINK, "Decryption started.");
536 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
537 engine->decrypt(masterKey, getOptions());
539 INFO(SINK, "Decryption complete.");
540 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
544 INFO(SINK, "Syncing disk and rebooting.");
546 ::reboot(RB_AUTOBOOT);
547 } catch (runtime::Exception &e) {
548 ERROR(SINK, "Decryption failed: " + std::string(e.what()));
552 std::thread asyncWork(decryptWorker);
558 int InternalEncryptionServer::recovery()
560 int state = getState();
562 if (state == State::Unencrypted)
563 return error::NoSuchDevice;
565 runtime::File file("/opt/.factoryreset");
570 dbus::Connection& systemDBus = dbus::Connection::getSystem();
571 systemDBus.methodcall("org.tizen.system.deviced",
572 "/Org/Tizen/System/DeviceD/Power",
573 "org.tizen.system.deviced.power",
575 -1, "()", "(si)", "reboot", 0);
576 } catch (runtime::Exception &e) {
577 ::reboot(RB_AUTOBOOT);
582 int InternalEncryptionServer::isPasswordInitialized()
584 return keyServer.isInitialized(engine->getSource());
587 int InternalEncryptionServer::initPassword(const std::string& password)
589 return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
592 int InternalEncryptionServer::cleanPassword(const std::string& password)
594 return keyServer.remove(engine->getSource(), password);
597 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
598 const std::string& newPassword)
600 return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
603 int InternalEncryptionServer::verifyPassword(const std::string& password)
605 return keyServer.verifyPassword(engine->getSource(), password);
608 int InternalEncryptionServer::getState()
610 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
612 throw runtime::Exception("Failed to get vconf value.");
615 std::string valueStr(value);
618 if (valueStr == "encrypted")
619 return State::Encrypted;
620 else if (valueStr == "unencrypted")
621 return State::Unencrypted;
622 else if (valueStr == "error_partially_encrypted" || valueStr == "error_partially_decrypted")
623 return State::Corrupted;
625 return State::Invalid;
628 unsigned int InternalEncryptionServer::getSupportedOptions()
630 return engine->getSupportedOptions();
633 std::string InternalEncryptionServer::getDevicePath() const
635 return engine->getSource();