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 "internal-encryption.h"
47 #include "internal-encryption-common.h"
53 const char *PRIVILEGE_PLATFORM = "http://tizen.org/privilege/internal/default/platform";
55 // watches systemd jobs
58 explicit JobWatch(dbus::Connection& systemDBus);
61 bool waitForJob(const std::string& job);
64 void jobRemoved(const dbus::Variant& parameters);
68 const std::string& job,
69 const std::string& unit,
70 const std::string& result) : id(id), job(job), unit(unit), result(result) {}
77 dbus::Connection::SubscriptionId id;
78 dbus::Connection& systemDBus;
79 std::list<Job> removedJobs;
81 std::condition_variable jobsCv;
84 JobWatch::JobWatch(dbus::Connection& systemDBus) : systemDBus(systemDBus) {
85 auto callback = [this](dbus::Variant parameters) {
86 this->jobRemoved(parameters);
89 id = systemDBus.subscribeSignal("",
90 "/org/freedesktop/systemd1",
91 "org.freedesktop.systemd1.Manager",
96 JobWatch::~JobWatch() {
97 systemDBus.unsubscribeSignal(id);
100 bool JobWatch::waitForJob(const std::string& job) {
102 std::unique_lock<std::mutex> lock(jobsMutex);
103 jobsCv.wait(lock, [this]{ return !removedJobs.empty(); });
105 while(!removedJobs.empty()) {
106 bool match = (removedJobs.front().job == job);
107 bool done = (removedJobs.front().result == "done");
108 removedJobs.pop_front();
115 void JobWatch::jobRemoved(const dbus::Variant& parameters)
121 parameters.get("(uoss)", &id, &job, &unit, &result);
122 INFO(SINK, "id:" + std::to_string(id) + " job:" + job + " unit:" + unit + " result:" + result);
125 std::lock_guard<std::mutex> guard(jobsMutex);
126 removedJobs.emplace_back(id, job, unit, result);
131 void stopKnownSystemdUnits()
133 std::vector<std::string> knownSystemdUnits;
134 dbus::Connection& systemDBus = dbus::Connection::getSystem();
135 dbus::VariantIterator iter;
137 systemDBus.methodcall("org.freedesktop.systemd1",
138 "/org/freedesktop/systemd1",
139 "org.freedesktop.systemd1.Manager",
141 -1, "(a(ssssssouso))", "")
142 .get("(a(ssssssouso))", &iter);
145 unsigned int dataUint;
149 ret = iter.get("(ssssssouso)", dataStr, dataStr + 1, dataStr + 2,
150 dataStr + 3, dataStr + 4, dataStr + 5,
151 dataStr + 6, &dataUint, dataStr + 7,
158 std::string unit(dataStr[0]);
159 if (unit == "security-manager.socket") {
160 knownSystemdUnits.insert(knownSystemdUnits.begin(), unit);
161 } else if (unit.compare(0, 5, "user@") == 0 ||
162 unit == "tlm.service" ||
163 unit == "resourced.service" ||
164 unit == "security-manager.service") {
165 knownSystemdUnits.push_back(unit);
169 JobWatch watch(systemDBus);
171 for (const std::string& unit : knownSystemdUnits) {
172 INFO(SINK, "Stopping unit: " + unit);
173 const char* job = NULL;
174 systemDBus.methodcall("org.freedesktop.systemd1",
175 "/org/freedesktop/systemd1",
176 "org.freedesktop.systemd1.Manager",
178 -1, "(o)", "(ss)", unit.c_str(), "flush").get("(o)", &job);
179 INFO(SINK, "Waiting for job: " + std::string(job));
180 if (!watch.waitForJob(job))
181 throw runtime::Exception("Stopping unit: " + unit + " failed");
185 void stopDependedSystemdUnits()
187 dbus::Connection& systemDBus = dbus::Connection::getSystem();
188 std::set<std::string> unitsToStop;
190 for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
193 systemDBus.methodcall("org.freedesktop.systemd1",
194 "/org/freedesktop/systemd1",
195 "org.freedesktop.systemd1.Manager",
197 -1, "(o)", "(u)", (unsigned int)pid)
199 unitsToStop.insert(unit);
200 } catch (runtime::Exception &e) {
201 INFO(SINK, "Killing process: " + std::to_string(pid));
202 ::kill(pid, SIGKILL);
206 JobWatch watch(systemDBus);
208 for (const std::string& unit : unitsToStop) {
209 INFO(SINK, "Stopping unit: " + unit);
210 const char* job = NULL;
211 systemDBus.methodcall("org.freedesktop.systemd1",
213 "org.freedesktop.systemd1.Unit",
215 -1, "(o)", "(s)", "flush").get("(o)", &job);
216 INFO(SINK, "Waiting for job: " + std::string(job));
217 if (!watch.waitForJob(job))
218 throw runtime::Exception("Stopping unit: " + unit + " failed");
222 void showProgressUI(const std::string type)
224 dbus::Connection& systemDBus = dbus::Connection::getSystem();
225 std::string unit("ode-progress-ui@"+type+".service");
227 JobWatch watch(systemDBus);
228 INFO(SINK, "Start unit: " + unit);
230 const char* job = NULL;
231 systemDBus.methodcall("org.freedesktop.systemd1",
232 "/org/freedesktop/systemd1",
233 "org.freedesktop.systemd1.Manager",
235 -1, "(o)", "(ss)", unit.c_str(), "replace").get("(o)", &job);
237 INFO(SINK, "Waiting for job: " + std::string(job));
238 if (!watch.waitForJob(job))
239 throw runtime::Exception("Starting unit: " + unit + " failed");
242 unsigned int getOptions()
244 unsigned int result = 0;
248 ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
250 result |= InternalEncryption::Option::IncludeUnusedRegion;
256 void setOptions(unsigned int options)
260 if (options & InternalEncryption::Option::IncludeUnusedRegion) {
265 ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
268 void unmountInternalStorage(const std::string& source)
271 auto mntPaths = findMountPointsByDevice(source);
275 bool unmounted = true;
276 for(const auto& path : mntPaths) {
277 INFO(SINK, "Unmounting " + path);
278 if (::umount(path.c_str()) == -1) {
279 // If it's busy or was already unmounted ignore the error
280 if (errno != EBUSY && errno != EINVAL) {
281 throw runtime::Exception("umount() error: " + runtime::GetSystemErrorMessage());
287 stopDependedSystemdUnits();
293 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv,
298 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
299 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)());
300 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
301 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
302 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
303 server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
304 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::recovery)());
305 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
306 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
307 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
308 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
309 server.expose(this, "", (int)(InternalEncryptionServer::getState)());
310 server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
311 server.expose(this, "", (std::string)(InternalEncryptionServer::getDevicePath)());
313 server.createNotification("InternalEncryptionServer::mount");
315 std::string source = findDevPath();
317 engine.reset(new INTERNAL_ENGINE(
318 source, INTERNAL_PATH,
319 ProgressBar([](int v) {
320 ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
321 std::to_string(v).c_str());
326 InternalEncryptionServer::~InternalEncryptionServer()
330 int InternalEncryptionServer::setMountPassword(const std::string& password)
332 return keyServer.get(engine->getSource(), password, mountKey);
335 int InternalEncryptionServer::mount()
337 if (mountKey.empty()) {
338 ERROR(SINK, "You need to call set_mount_password() first.");
339 return error::NoData;
342 BinaryData key = mountKey;
345 if (getState() != State::Encrypted) {
346 INFO(SINK, "Cannot mount, SD partition's state incorrect.");
347 return error::NoSuchDevice;
350 if (engine->isMounted()) {
351 INFO(SINK, "Partition already mounted.");
355 INFO(SINK, "Mounting internal storage.");
357 engine->mount(key, getOptions());
359 server.notify("InternalEncryptionServer::mount");
361 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
362 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
363 } catch (runtime::Exception &e) {
364 ERROR(SINK, "Mount failed: " + std::string(e.what()));
365 return error::Unknown;
371 int InternalEncryptionServer::umount()
373 if (getState() != State::Encrypted) {
374 ERROR(SINK, "Cannot umount, partition's state incorrect.");
375 return error::NoSuchDevice;
378 if (!engine->isMounted()) {
379 INFO(SINK, "Partition already umounted.");
383 INFO(SINK, "Closing all processes using internal storage.");
385 stopDependedSystemdUnits();
386 INFO(SINK, "Umounting internal storage.");
388 } catch (runtime::Exception &e) {
389 ERROR(SINK, "Umount failed: " + std::string(e.what()));
390 return error::Unknown;
396 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
398 if (getState() != State::Unencrypted) {
399 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
400 return error::NoSuchDevice;
403 BinaryData masterKey;
404 int ret = keyServer.get(engine->getSource(), password, masterKey);
405 if (ret != error::None)
408 auto encryptWorker = [masterKey, options, this]() {
410 showProgressUI("encrypt");
413 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
414 stopKnownSystemdUnits();
416 std::string source = engine->getSource();
417 auto mntPaths = findMountPointsByDevice(source);
419 if (!mntPaths.empty()) {
420 INFO(SINK, "Closing all processes using internal storage.");
421 stopDependedSystemdUnits();
423 INFO(SINK, "Unmounting internal storage.");
424 unmountInternalStorage(source);
427 INFO(SINK, "Encryption started.");
428 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
429 engine->encrypt(masterKey, options);
430 setOptions(options & getSupportedOptions());
432 INFO(SINK, "Encryption completed.");
433 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
434 server.notify("InternalEncryptionServer::mount");
436 INFO(SINK, "Syncing disk and rebooting.");
438 ::reboot(RB_AUTOBOOT);
439 } catch (runtime::Exception &e) {
440 ERROR(SINK, "Encryption failed: " + std::string(e.what()));
444 std::thread asyncWork(encryptWorker);
450 int InternalEncryptionServer::decrypt(const std::string& password)
452 if (getState() != State::Encrypted) {
453 ERROR(SINK, "Cannot decrypt, 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 decryptWorker = [masterKey, this]() {
464 showProgressUI("decrypt");
467 if (engine->isMounted()) {
468 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
469 stopKnownSystemdUnits();
470 INFO(SINK, "Closing all processes using internal storage.");
471 stopDependedSystemdUnits();
473 INFO(SINK, "Umounting internal storage.");
478 } catch (runtime::Exception& e) {
479 stopDependedSystemdUnits();
484 INFO(SINK, "Decryption started.");
485 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
486 engine->decrypt(masterKey, getOptions());
488 INFO(SINK, "Decryption complete.");
489 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
491 INFO(SINK, "Syncing disk and rebooting.");
493 ::reboot(RB_AUTOBOOT);
494 } catch (runtime::Exception &e) {
495 ERROR(SINK, "Decryption failed: " + std::string(e.what()));
499 std::thread asyncWork(decryptWorker);
505 int InternalEncryptionServer::recovery()
507 int state = getState();
509 if (state == State::Unencrypted)
510 return error::NoSuchDevice;
512 if (state == State::Corrupted) {
513 const char *mkfsPath = "/sbin/mkfs.ext4";
514 std::vector<std::string> formatArg = {
515 mkfsPath, "-F", engine->getSource()};
516 runtime::Process proc(mkfsPath, formatArg);
518 int ret = proc.execute();
520 throw runtime::Exception("Failed to execute mkfs.ext4");
522 ret = proc.waitForFinished();
523 if (ret < 0 || !WIFEXITED(ret) || WEXITSTATUS(ret) != 0)
524 throw runtime::Exception("Failed to wait for finish of format");
528 fs.open("/opt/.factoryreset", std::ios::out);
533 dbus::Connection& systemDBus = dbus::Connection::getSystem();
534 systemDBus.methodcall("org.tizen.deviced",
535 "/Org/Tizen/DeviceD/Power",
536 "org.tizen.deviced.power",
538 -1, "()", "(si)", "reboot", 0);
539 } catch (runtime::Exception &e) {
540 ::reboot(RB_AUTOBOOT);
545 int InternalEncryptionServer::isPasswordInitialized()
547 return keyServer.isInitialized(engine->getSource());
550 int InternalEncryptionServer::initPassword(const std::string& password)
552 return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
555 int InternalEncryptionServer::cleanPassword(const std::string& password)
557 return keyServer.remove(engine->getSource(), password);
560 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
561 const std::string& newPassword)
563 return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
566 int InternalEncryptionServer::verifyPassword(const std::string& password)
568 return keyServer.verifyPassword(engine->getSource(), password);
571 int InternalEncryptionServer::getState()
573 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
575 throw runtime::Exception("Failed to get vconf value.");
578 std::string valueStr(value);
581 if (valueStr == "encrypted") {
582 return State::Encrypted;
583 } else if (valueStr == "unencrypted") {
584 return State::Unencrypted;
586 return State::Corrupted;
590 unsigned int InternalEncryptionServer::getSupportedOptions()
592 return engine->getSupportedOptions();
595 std::string InternalEncryptionServer::getDevicePath() const
597 return engine->getSource();