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 stopDependedSystemdUnits()
160 dbus::Connection& systemDBus = dbus::Connection::getSystem();
161 std::set<std::string> unitsToStop;
163 for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
165 char *unit = nullptr;
166 systemDBus.methodcall("org.freedesktop.systemd1",
167 "/org/freedesktop/systemd1",
168 "org.freedesktop.systemd1.Manager",
170 -1, "(o)", "(u)", (unsigned int)pid)
173 auto unescapedName = getDecodedPath(unit, "/org/freedesktop/systemd1/unit/");
174 unitsToStop.insert(unescapedName);
175 } catch (runtime::Exception &e) {
176 INFO(SINK, "Killing process: " + std::to_string(pid));
177 ::kill(pid, SIGKILL);
181 JobWatch watch(systemDBus);
182 for (auto unit : blackListSystemdUnits) {
183 unitsToStop.erase(unitsToStop.find(unit));
186 for (const std::string& unit : unitsToStop) {
187 INFO(SINK, "Stopping unit: " + unit);
188 const char* job = NULL;
189 systemDBus.methodcall("org.freedesktop.systemd1",
190 "/org/freedesktop/systemd1",
191 "org.freedesktop.systemd1.Manager",
193 -1, "(o)", "(ss)", unit.c_str(), "flush").get("(o)", &job);
194 INFO(SINK, "Waiting for job: " + std::string(job));
195 if (!watch.waitForJob(job))
196 throw runtime::Exception("Stopping unit: " + unit + " failed");
200 void showProgressUI(const std::string type)
202 dbus::Connection& systemDBus = dbus::Connection::getSystem();
203 std::string unit("ode-progress-ui@"+type+".service");
205 JobWatch watch(systemDBus);
206 INFO(SINK, "Start unit: " + unit);
208 const char* job = NULL;
209 systemDBus.methodcall("org.freedesktop.systemd1",
210 "/org/freedesktop/systemd1",
211 "org.freedesktop.systemd1.Manager",
213 -1, "(o)", "(ss)", unit.c_str(), "replace").get("(o)", &job);
215 INFO(SINK, "Waiting for job: " + std::string(job));
216 if (!watch.waitForJob(job))
217 throw runtime::Exception("Starting unit: " + unit + " failed");
220 unsigned int getOptions()
222 unsigned int result = 0;
226 ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
228 result |= InternalEncryption::Option::IncludeUnusedRegion;
234 void setOptions(unsigned int options)
238 if (options & InternalEncryption::Option::IncludeUnusedRegion) {
243 ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
246 void execAndWait(const std::string &path, std::vector<std::string> &args)
248 runtime::Process proc(path, args);
249 int ret = proc.execute();
251 ERROR(SINK, path + " failed for " + args.back());
253 ret = proc.waitForFinished();
254 if (ret < 0 || !WIFEXITED(ret) || WEXITSTATUS(ret) != 0)
255 ERROR(SINK, path + " failed for " + args.back());
258 bool isPartitionTerminated(const std::string &partition)
261 const std::string cmd("fuser -m " + partition + " | grep -o '[0-9]*'");
262 char *line = nullptr;
265 FILE *fp = ::popen(cmd.c_str(), "r");
267 ERROR(SINK, "Failed to get processes on partition");
271 if (::getline(&line, &len, fp) != -1)
280 void unmountInternalStorage(const std::string& source)
282 if (::umount2("/opt/usr", MNT_DETACH) == -1) {
283 if (errno != EBUSY && errno != EINVAL) {
284 throw runtime::Exception("umount() error : " + runtime::GetSystemErrorMessage());
290 static const char *fuserPath = "/usr/bin/fuser";
291 std::vector<std::string> args = {
292 fuserPath, "-m", "-k", "-s", "-SIGTERM", source,
294 execAndWait(fuserPath, args);
295 ::usleep((useconds_t)((unsigned int)(500)*1000));
297 args[4] = "-SIGKILL";
298 execAndWait(fuserPath, args);
299 ::usleep((useconds_t)((unsigned int)(200)*1000));
300 } while (!isPartitionTerminated(source));
305 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv,
310 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
311 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)(std::vector<unsigned char>, unsigned int));
312 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
313 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::isMounted)());
314 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
315 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
316 server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
317 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::recovery)());
318 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
319 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
320 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
321 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
322 server.expose(this, "", (int)(InternalEncryptionServer::getState)());
323 server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
324 server.expose(this, "", (std::string)(InternalEncryptionServer::getDevicePath)());
326 server.createNotification("InternalEncryptionServer::mount");
328 std::string source = findDevPath();
330 engine.reset(new INTERNAL_ENGINE(
331 source, INTERNAL_PATH,
332 ProgressBar([](int v) {
333 ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
334 std::to_string(v).c_str());
339 InternalEncryptionServer::~InternalEncryptionServer()
343 int InternalEncryptionServer::setMountPassword(const std::string& password)
345 const std::string& dev = engine->getSource();
347 // check if upgrade flag exists
348 if(UpgradeSupport::removeUpgradeFlag()) {
349 INFO("Upgrade flag detected.");
350 // try to load the master key
352 mountKey = UpgradeSupport::loadMasterKey(dev);
354 // encrypt the master key with given password
355 return keyServer.changePassword2(dev, mountKey, password);
356 } catch (const runtime::Exception&) {
357 INFO("Failed to load the master key stored during upgrade.");
361 return keyServer.get(dev, password, mountKey);
364 int InternalEncryptionServer::mount(const std::vector<unsigned char> &mk, unsigned int options)
366 if (mountKey.empty() && mk.empty()) {
367 ERROR(SINK, "You need to set master key first.");
368 return error::NoData;
371 BinaryData key = mk.empty() ? mountKey : mk;
374 if (getState() != State::Encrypted) {
375 INFO(SINK, "Cannot mount, SD partition's state incorrect.");
376 return error::NoSuchDevice;
379 if (engine->isMounted()) {
380 INFO(SINK, "Partition already mounted.");
384 INFO(SINK, "Mounting internal storage.");
386 engine->mount(key, getOptions());
388 server.notify("InternalEncryptionServer::mount");
390 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
391 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
392 } catch (runtime::Exception &e) {
393 ERROR(SINK, "Mount failed: " + std::string(e.what()));
394 return error::Unknown;
400 int InternalEncryptionServer::isMounted()
404 ret = engine->isMounted() ? 1 : 0;
405 } catch (runtime::Exception &e) {
406 ERROR(SINK, "Failed to access the mount flag");
407 return error::Unknown;
412 int InternalEncryptionServer::umount()
414 if (getState() != State::Encrypted) {
415 ERROR(SINK, "Cannot umount, partition's state incorrect.");
416 return error::NoSuchDevice;
419 if (!engine->isMounted()) {
420 INFO(SINK, "Partition already umounted.");
424 INFO(SINK, "Closing all processes using internal storage.");
426 stopDependedSystemdUnits();
427 INFO(SINK, "Umounting internal storage.");
428 unmountInternalStorage("/dev/mapper/userdata");
430 } catch (runtime::Exception &e) {
431 ERROR(SINK, "Umount failed: " + std::string(e.what()));
432 return error::Unknown;
438 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
440 if (getState() != State::Unencrypted) {
441 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
442 return error::NoSuchDevice;
445 BinaryData masterKey;
446 int ret = keyServer.get(engine->getSource(), password, masterKey);
447 if (ret != error::None)
450 auto encryptWorker = [masterKey, options, this]() {
452 showProgressUI("encrypt");
455 runtime::File file("/opt/etc/.odeprogress");
458 std::string source = engine->getSource();
459 auto mntPaths = findMountPointsByDevice(source);
461 if (!mntPaths.empty()) {
462 INFO(SINK, "Closing all processes using internal storage.");
463 stopDependedSystemdUnits();
465 INFO(SINK, "Unmounting internal storage.");
466 unmountInternalStorage(source);
469 INFO(SINK, "Encryption started.");
470 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
471 engine->encrypt(masterKey, options);
472 setOptions(options & getSupportedOptions());
474 INFO(SINK, "Encryption completed.");
475 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
476 server.notify("InternalEncryptionServer::mount");
480 INFO(SINK, "Syncing disk and rebooting.");
482 ::reboot(RB_AUTOBOOT);
483 } catch (runtime::Exception &e) {
484 ERROR(SINK, "Encryption failed: " + std::string(e.what()));
488 std::thread asyncWork(encryptWorker);
494 int InternalEncryptionServer::decrypt(const std::string& password)
496 if (getState() != State::Encrypted) {
497 ERROR(SINK, "Cannot decrypt, 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 decryptWorker = [masterKey, this]() {
508 showProgressUI("decrypt");
511 runtime::File file("/opt/etc/.odeprogress");
514 if (engine->isMounted()) {
515 INFO(SINK, "Closing all processes using internal storage.");
516 stopDependedSystemdUnits();
518 INFO(SINK, "Umounting internal storage.");
519 unmountInternalStorage("/dev/mapper/userdata");
523 INFO(SINK, "Decryption started.");
524 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
525 engine->decrypt(masterKey, getOptions());
527 INFO(SINK, "Decryption complete.");
528 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
532 INFO(SINK, "Syncing disk and rebooting.");
534 ::reboot(RB_AUTOBOOT);
535 } catch (runtime::Exception &e) {
536 ERROR(SINK, "Decryption failed: " + std::string(e.what()));
540 std::thread asyncWork(decryptWorker);
546 int InternalEncryptionServer::recovery()
548 int state = getState();
550 if (state == State::Unencrypted)
551 return error::NoSuchDevice;
553 runtime::File file("/opt/.factoryreset");
558 dbus::Connection& systemDBus = dbus::Connection::getSystem();
559 systemDBus.methodcall("org.tizen.system.deviced",
560 "/Org/Tizen/System/DeviceD/Power",
561 "org.tizen.system.deviced.power",
563 -1, "()", "(si)", "reboot", 0);
564 } catch (runtime::Exception &e) {
565 ::reboot(RB_AUTOBOOT);
570 int InternalEncryptionServer::isPasswordInitialized()
572 return keyServer.isInitialized(engine->getSource());
575 int InternalEncryptionServer::initPassword(const std::string& password)
577 return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
580 int InternalEncryptionServer::cleanPassword(const std::string& password)
582 return keyServer.remove(engine->getSource(), password);
585 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
586 const std::string& newPassword)
588 return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
591 int InternalEncryptionServer::verifyPassword(const std::string& password)
593 return keyServer.verifyPassword(engine->getSource(), password);
596 int InternalEncryptionServer::getState()
598 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
600 throw runtime::Exception("Failed to get vconf value.");
603 std::string valueStr(value);
606 if (valueStr == "encrypted")
607 return State::Encrypted;
608 else if (valueStr == "unencrypted")
609 return State::Unencrypted;
610 else if (valueStr == "error_partially_encrypted" || valueStr == "error_partially_decrypted")
611 return State::Corrupted;
613 return State::Invalid;
616 unsigned int InternalEncryptionServer::getSupportedOptions()
618 return engine->getSupportedOptions();
621 std::string InternalEncryptionServer::getDevicePath() const
623 return engine->getSource();