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 auto stopUnit = [&systemDBus](const std::string &unit) {
195 INFO(SINK, "Stopping unit: " + unit);
196 JobWatch watch(systemDBus);
197 const char* job = NULL;
198 systemDBus.methodcall("org.freedesktop.systemd1",
199 "/org/freedesktop/systemd1",
200 "org.freedesktop.systemd1.Manager",
202 -1, "(o)", "(ss)", unit.c_str(), "flush").get("(o)", &job);
203 INFO(SINK, "Waiting for job: " + std::string(job));
204 if (!watch.waitForJob(job))
205 ERROR(SINK, "Stopping unit: " + unit + " failed");
208 for (const std::string &unit : preprocessUnits) {
212 for (const std::string &unit : unitsToStop) {
217 void showProgressUI(const std::string type)
219 dbus::Connection& systemDBus = dbus::Connection::getSystem();
220 std::string unit("ode-progress-ui@"+type+".service");
222 JobWatch watch(systemDBus);
223 INFO(SINK, "Start unit: " + unit);
225 const char* job = NULL;
226 systemDBus.methodcall("org.freedesktop.systemd1",
227 "/org/freedesktop/systemd1",
228 "org.freedesktop.systemd1.Manager",
230 -1, "(o)", "(ss)", unit.c_str(), "replace").get("(o)", &job);
232 INFO(SINK, "Waiting for job: " + std::string(job));
233 if (!watch.waitForJob(job))
234 ERROR(SINK, "Starting unit: " + unit + " failed");
237 unsigned int getOptions()
239 unsigned int result = 0;
243 ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
245 result |= InternalEncryption::Option::IncludeUnusedRegion;
251 void setOptions(unsigned int options)
255 if (options & InternalEncryption::Option::IncludeUnusedRegion) {
260 ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
263 void execAndWait(const std::string &path, std::vector<std::string> &args)
265 runtime::Process proc(path, args);
266 int ret = proc.execute();
268 ERROR(SINK, path + " failed for " + args.back());
270 ret = proc.waitForFinished();
271 if (ret < 0 || !WIFEXITED(ret) || WEXITSTATUS(ret) != 0)
272 ERROR(SINK, path + " failed for " + args.back());
275 bool isPartitionTerminated(const std::string &partition)
278 const std::string cmd("fuser -m " + partition + " | grep -o '[0-9]*'");
279 char *line = nullptr;
282 FILE *fp = ::popen(cmd.c_str(), "r");
284 ERROR(SINK, "Failed to get processes on partition");
288 if (::getline(&line, &len, fp) != -1)
297 void unmountInternalStorage(const std::string& source)
299 if (::umount2("/opt/usr", MNT_DETACH) == -1) {
300 if (errno != EBUSY && errno != EINVAL) {
301 throw runtime::Exception("umount() error : " + runtime::GetSystemErrorMessage());
307 static const char *fuserPath = "/usr/bin/fuser";
308 std::vector<std::string> args = {
309 fuserPath, "-m", "-k", "-s", "-SIGTERM", source,
311 execAndWait(fuserPath, args);
312 ::usleep((useconds_t)((unsigned int)(500)*1000));
314 args[4] = "-SIGKILL";
315 execAndWait(fuserPath, args);
316 ::usleep((useconds_t)((unsigned int)(200)*1000));
317 } while (!isPartitionTerminated(source));
322 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv,
327 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
328 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)(std::vector<unsigned char>, unsigned int));
329 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
330 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::isMounted)());
331 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
332 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
333 server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
334 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::recovery)());
335 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
336 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
337 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
338 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
339 server.expose(this, "", (int)(InternalEncryptionServer::getState)());
340 server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
341 server.expose(this, "", (std::string)(InternalEncryptionServer::getDevicePath)());
343 server.createNotification("InternalEncryptionServer::mount");
345 std::string source = findDevPath();
347 engine.reset(new INTERNAL_ENGINE(
348 source, INTERNAL_PATH,
349 ProgressBar([](int v) {
350 ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
351 std::to_string(v).c_str());
356 InternalEncryptionServer::~InternalEncryptionServer()
360 int InternalEncryptionServer::setMountPassword(const std::string& password)
362 const std::string& dev = engine->getSource();
364 // check if upgrade flag exists
365 if(UpgradeSupport::removeUpgradeFlag()) {
366 INFO("Upgrade flag detected.");
367 // try to load the master key
369 mountKey = UpgradeSupport::loadMasterKey(dev);
371 // encrypt the master key with given password
372 return keyServer.changePassword2(dev, mountKey, password);
373 } catch (const runtime::Exception&) {
374 INFO("Failed to load the master key stored during upgrade.");
378 return keyServer.get(dev, password, mountKey);
381 int InternalEncryptionServer::mount(const std::vector<unsigned char> &mk, unsigned int options)
383 if (mountKey.empty() && mk.empty()) {
384 ERROR(SINK, "You need to set master key first.");
385 return error::NoData;
388 BinaryData key = mk.empty() ? mountKey : mk;
391 if (getState() != State::Encrypted) {
392 INFO(SINK, "Cannot mount, SD partition's state incorrect.");
393 return error::NoSuchDevice;
396 if (engine->isMounted()) {
397 INFO(SINK, "Partition already mounted.");
401 INFO(SINK, "Mounting internal storage.");
403 engine->mount(key, getOptions());
405 server.notify("InternalEncryptionServer::mount");
407 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
408 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
409 } catch (runtime::Exception &e) {
410 ERROR(SINK, "Mount failed: " + std::string(e.what()));
411 return error::Unknown;
417 int InternalEncryptionServer::isMounted()
421 ret = engine->isMounted() ? 1 : 0;
422 } catch (runtime::Exception &e) {
423 ERROR(SINK, "Failed to access the mount flag");
424 return error::Unknown;
429 int InternalEncryptionServer::umount()
431 if (getState() != State::Encrypted) {
432 ERROR(SINK, "Cannot umount, partition's state incorrect.");
433 return error::NoSuchDevice;
436 if (!engine->isMounted()) {
437 INFO(SINK, "Partition already umounted.");
441 INFO(SINK, "Closing all processes using internal storage.");
444 INFO(SINK, "Umounting internal storage.");
445 unmountInternalStorage("/dev/mapper/userdata");
447 } catch (runtime::Exception &e) {
448 ERROR(SINK, "Umount failed: " + std::string(e.what()));
449 return error::Unknown;
455 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
457 if (getState() != State::Unencrypted) {
458 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
459 return error::NoSuchDevice;
462 BinaryData masterKey;
463 int ret = keyServer.get(engine->getSource(), password, masterKey);
464 if (ret != error::None)
467 auto encryptWorker = [masterKey, options, this]() {
469 showProgressUI("encrypt");
472 runtime::File file("/opt/etc/.odeprogress");
475 std::string source = engine->getSource();
476 auto mntPaths = findMountPointsByDevice(source);
478 if (!mntPaths.empty()) {
479 INFO(SINK, "Closing all processes using internal storage.");
482 INFO(SINK, "Unmounting internal storage.");
483 unmountInternalStorage(source);
486 INFO(SINK, "Encryption started.");
487 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
488 engine->encrypt(masterKey, options);
489 setOptions(options & getSupportedOptions());
491 INFO(SINK, "Encryption completed.");
492 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
493 server.notify("InternalEncryptionServer::mount");
497 INFO(SINK, "Syncing disk and rebooting.");
499 ::reboot(RB_AUTOBOOT);
500 } catch (runtime::Exception &e) {
501 ERROR(SINK, "Encryption failed: " + std::string(e.what()));
505 std::thread asyncWork(encryptWorker);
511 int InternalEncryptionServer::decrypt(const std::string& password)
513 if (getState() != State::Encrypted) {
514 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
515 return error::NoSuchDevice;
518 BinaryData masterKey;
519 int ret = keyServer.get(engine->getSource(), password, masterKey);
520 if (ret != error::None)
523 auto decryptWorker = [masterKey, this]() {
525 showProgressUI("decrypt");
528 runtime::File file("/opt/etc/.odeprogress");
531 if (engine->isMounted()) {
532 INFO(SINK, "Closing all processes using internal storage.");
535 INFO(SINK, "Umounting internal storage.");
536 unmountInternalStorage("/dev/mapper/userdata");
540 INFO(SINK, "Decryption started.");
541 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
542 engine->decrypt(masterKey, getOptions());
544 INFO(SINK, "Decryption complete.");
545 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
549 INFO(SINK, "Syncing disk and rebooting.");
551 ::reboot(RB_AUTOBOOT);
552 } catch (runtime::Exception &e) {
553 ERROR(SINK, "Decryption failed: " + std::string(e.what()));
557 std::thread asyncWork(decryptWorker);
563 int InternalEncryptionServer::recovery()
565 int state = getState();
567 if (state == State::Unencrypted)
568 return error::NoSuchDevice;
570 runtime::File file("/opt/.factoryreset");
575 dbus::Connection& systemDBus = dbus::Connection::getSystem();
576 systemDBus.methodcall("org.tizen.system.deviced",
577 "/Org/Tizen/System/DeviceD/Power",
578 "org.tizen.system.deviced.power",
580 -1, "()", "(si)", "reboot", 0);
581 } catch (runtime::Exception &e) {
582 ::reboot(RB_AUTOBOOT);
587 int InternalEncryptionServer::isPasswordInitialized()
589 return keyServer.isInitialized(engine->getSource());
592 int InternalEncryptionServer::initPassword(const std::string& password)
594 return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
597 int InternalEncryptionServer::cleanPassword(const std::string& password)
599 return keyServer.remove(engine->getSource(), password);
602 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
603 const std::string& newPassword)
605 return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
608 int InternalEncryptionServer::verifyPassword(const std::string& password)
610 return keyServer.verifyPassword(engine->getSource(), password);
613 int InternalEncryptionServer::getState()
615 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
617 throw runtime::Exception("Failed to get vconf value.");
620 std::string valueStr(value);
623 if (valueStr == "encrypted")
624 return State::Encrypted;
625 else if (valueStr == "unencrypted")
626 return State::Unencrypted;
627 else if (valueStr == "error_partially_encrypted" || valueStr == "error_partially_decrypted")
628 return State::Corrupted;
630 return State::Invalid;
633 unsigned int InternalEncryptionServer::getSupportedOptions()
635 return engine->getSupportedOptions();
638 std::string InternalEncryptionServer::getDevicePath() const
640 return engine->getSource();