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"
54 const char *PRIVILEGE_PLATFORM = "http://tizen.org/privilege/internal/default/platform";
56 // watches systemd jobs
59 explicit JobWatch(dbus::Connection& systemDBus);
62 bool waitForJob(const std::string& job);
65 void jobRemoved(const dbus::Variant& parameters);
69 const std::string& job,
70 const std::string& unit,
71 const std::string& result) : id(id), job(job), unit(unit), result(result) {}
78 dbus::Connection::SubscriptionId id;
79 dbus::Connection& systemDBus;
80 std::list<Job> removedJobs;
82 std::condition_variable jobsCv;
85 JobWatch::JobWatch(dbus::Connection& systemDBus) : systemDBus(systemDBus) {
86 auto callback = [this](dbus::Variant parameters) {
87 this->jobRemoved(parameters);
90 id = systemDBus.subscribeSignal("",
91 "/org/freedesktop/systemd1",
92 "org.freedesktop.systemd1.Manager",
97 JobWatch::~JobWatch() {
98 systemDBus.unsubscribeSignal(id);
101 bool JobWatch::waitForJob(const std::string& job) {
103 std::unique_lock<std::mutex> lock(jobsMutex);
104 jobsCv.wait(lock, [this]{ return !removedJobs.empty(); });
106 while(!removedJobs.empty()) {
107 bool match = (removedJobs.front().job == job);
108 bool done = (removedJobs.front().result == "done");
109 removedJobs.pop_front();
116 void JobWatch::jobRemoved(const dbus::Variant& parameters)
122 parameters.get("(uoss)", &id, &job, &unit, &result);
123 INFO(SINK, "id:" + std::to_string(id) + " job:" + job + " unit:" + unit + " result:" + result);
126 std::lock_guard<std::mutex> guard(jobsMutex);
127 removedJobs.emplace_back(id, job, unit, result);
132 void stopKnownSystemdUnits()
134 std::vector<std::string> knownSystemdUnits;
135 dbus::Connection& systemDBus = dbus::Connection::getSystem();
136 dbus::VariantIterator iter;
138 systemDBus.methodcall("org.freedesktop.systemd1",
139 "/org/freedesktop/systemd1",
140 "org.freedesktop.systemd1.Manager",
142 -1, "(a(ssssssouso))", "")
143 .get("(a(ssssssouso))", &iter);
146 unsigned int dataUint;
150 ret = iter.get("(ssssssouso)", dataStr, dataStr + 1, dataStr + 2,
151 dataStr + 3, dataStr + 4, dataStr + 5,
152 dataStr + 6, &dataUint, dataStr + 7,
159 std::string unit(dataStr[0]);
160 if (unit == "security-manager.socket") {
161 knownSystemdUnits.insert(knownSystemdUnits.begin(), unit);
162 } else if (unit.compare(0, 5, "user@") == 0 ||
163 unit == "tlm.service" ||
164 unit == "resourced.service" ||
165 unit == "security-manager.service") {
166 knownSystemdUnits.push_back(unit);
170 JobWatch watch(systemDBus);
172 for (const std::string& unit : knownSystemdUnits) {
173 INFO(SINK, "Stopping unit: " + unit);
174 const char* job = NULL;
175 systemDBus.methodcall("org.freedesktop.systemd1",
176 "/org/freedesktop/systemd1",
177 "org.freedesktop.systemd1.Manager",
179 -1, "(o)", "(ss)", unit.c_str(), "flush").get("(o)", &job);
180 INFO(SINK, "Waiting for job: " + std::string(job));
181 if (!watch.waitForJob(job))
182 throw runtime::Exception("Stopping unit: " + unit + " failed");
186 void stopDependedSystemdUnits()
188 dbus::Connection& systemDBus = dbus::Connection::getSystem();
189 std::set<std::string> unitsToStop;
191 for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
194 systemDBus.methodcall("org.freedesktop.systemd1",
195 "/org/freedesktop/systemd1",
196 "org.freedesktop.systemd1.Manager",
198 -1, "(o)", "(u)", (unsigned int)pid)
200 unitsToStop.insert(unit);
201 } catch (runtime::Exception &e) {
202 INFO(SINK, "Killing process: " + std::to_string(pid));
203 ::kill(pid, SIGKILL);
207 JobWatch watch(systemDBus);
209 for (const std::string& unit : unitsToStop) {
210 INFO(SINK, "Stopping unit: " + unit);
211 const char* job = NULL;
212 systemDBus.methodcall("org.freedesktop.systemd1",
214 "org.freedesktop.systemd1.Unit",
216 -1, "(o)", "(s)", "flush").get("(o)", &job);
217 INFO(SINK, "Waiting for job: " + std::string(job));
218 if (!watch.waitForJob(job))
219 throw runtime::Exception("Stopping unit: " + unit + " failed");
223 void showProgressUI(const std::string type)
225 dbus::Connection& systemDBus = dbus::Connection::getSystem();
226 std::string unit("ode-progress-ui@"+type+".service");
228 JobWatch watch(systemDBus);
229 INFO(SINK, "Start unit: " + unit);
231 const char* job = NULL;
232 systemDBus.methodcall("org.freedesktop.systemd1",
233 "/org/freedesktop/systemd1",
234 "org.freedesktop.systemd1.Manager",
236 -1, "(o)", "(ss)", unit.c_str(), "replace").get("(o)", &job);
238 INFO(SINK, "Waiting for job: " + std::string(job));
239 if (!watch.waitForJob(job))
240 throw runtime::Exception("Starting unit: " + unit + " failed");
243 unsigned int getOptions()
245 unsigned int result = 0;
249 ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
251 result |= InternalEncryption::Option::IncludeUnusedRegion;
257 void setOptions(unsigned int options)
261 if (options & InternalEncryption::Option::IncludeUnusedRegion) {
266 ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
269 void unmountInternalStorage(const std::string& source)
272 auto mntPaths = findMountPointsByDevice(source);
276 bool unmounted = true;
277 for(const auto& path : mntPaths) {
278 INFO(SINK, "Unmounting " + path);
279 if (::umount(path.c_str()) == -1) {
280 // If it's busy or was already unmounted ignore the error
281 if (errno != EBUSY && errno != EINVAL) {
282 throw runtime::Exception("umount() error: " + runtime::GetSystemErrorMessage());
288 stopDependedSystemdUnits();
294 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv, KeyServer& key) :
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");
360 } catch (runtime::Exception &e) {
361 ERROR(SINK, "Mount failed: " + std::string(e.what()));
362 return error::Unknown;
368 int InternalEncryptionServer::umount()
370 if (getState() != State::Encrypted) {
371 ERROR(SINK, "Cannot umount, partition's state incorrect.");
372 return error::NoSuchDevice;
375 if (!engine->isMounted()) {
376 INFO(SINK, "Partition already umounted.");
380 INFO(SINK, "Closing all processes using internal storage.");
382 stopDependedSystemdUnits();
383 INFO(SINK, "Umounting internal storage.");
385 } catch (runtime::Exception &e) {
386 ERROR(SINK, "Umount failed: " + std::string(e.what()));
387 return error::Unknown;
393 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
395 if (getState() != State::Unencrypted) {
396 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
397 return error::NoSuchDevice;
400 BinaryData masterKey;
401 int ret = keyServer.get(engine->getSource(), password, masterKey);
402 if (ret != error::None)
405 auto encryptWorker = [masterKey, options, this]() {
407 showProgressUI("encrypt");
410 runtime::File file("/opt/etc/.odeprogress");
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");
438 INFO(SINK, "Syncing disk and rebooting.");
440 ::reboot(RB_AUTOBOOT);
441 } catch (runtime::Exception &e) {
442 ERROR(SINK, "Encryption failed: " + std::string(e.what()));
446 std::thread asyncWork(encryptWorker);
452 int InternalEncryptionServer::decrypt(const std::string& password)
454 if (getState() != State::Encrypted) {
455 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
456 return error::NoSuchDevice;
459 BinaryData masterKey;
460 int ret = keyServer.get(engine->getSource(), password, masterKey);
461 if (ret != error::None)
464 auto decryptWorker = [masterKey, this]() {
466 showProgressUI("decrypt");
469 runtime::File file("/opt/etc/.odeprogress");
472 if (engine->isMounted()) {
473 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
474 stopKnownSystemdUnits();
475 INFO(SINK, "Closing all processes using internal storage.");
476 stopDependedSystemdUnits();
478 INFO(SINK, "Umounting internal storage.");
483 } catch (runtime::Exception& e) {
484 stopDependedSystemdUnits();
489 INFO(SINK, "Decryption started.");
490 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
491 engine->decrypt(masterKey, getOptions());
493 INFO(SINK, "Decryption complete.");
494 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
498 INFO(SINK, "Syncing disk and rebooting.");
500 ::reboot(RB_AUTOBOOT);
501 } catch (runtime::Exception &e) {
502 ERROR(SINK, "Decryption failed: " + std::string(e.what()));
506 std::thread asyncWork(decryptWorker);
512 int InternalEncryptionServer::recovery()
514 int state = getState();
516 if (state == State::Unencrypted)
517 return error::NoSuchDevice;
519 if (state == State::Corrupted)
520 Ext4Tool::mkfs(engine->getSource());
522 runtime::File file("/opt/.factoryreset");
527 dbus::Connection& systemDBus = dbus::Connection::getSystem();
528 systemDBus.methodcall("org.tizen.system.deviced",
529 "/Org/Tizen/System/DeviceD/Power",
530 "org.tizen.system.deviced.power",
532 -1, "()", "(si)", "reboot", 0);
533 } catch (runtime::Exception &e) {
534 ::reboot(RB_AUTOBOOT);
539 int InternalEncryptionServer::isPasswordInitialized()
541 return keyServer.isInitialized(engine->getSource());
544 int InternalEncryptionServer::initPassword(const std::string& password)
546 return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
549 int InternalEncryptionServer::cleanPassword(const std::string& password)
551 return keyServer.remove(engine->getSource(), password);
554 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
555 const std::string& newPassword)
557 return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
560 int InternalEncryptionServer::verifyPassword(const std::string& password)
562 return keyServer.verifyPassword(engine->getSource(), password);
565 int InternalEncryptionServer::getState()
567 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
569 throw runtime::Exception("Failed to get vconf value.");
572 std::string valueStr(value);
575 if (valueStr == "encrypted")
576 return State::Encrypted;
577 else if (valueStr == "unencrypted")
578 return State::Unencrypted;
579 else if (valueStr == "error_partially_encrypted" || valueStr == "error_partially_decrypted")
580 return State::Corrupted;
582 return State::Invalid;
585 unsigned int InternalEncryptionServer::getSupportedOptions()
587 return engine->getSupportedOptions();
590 std::string InternalEncryptionServer::getDevicePath() const
592 return engine->getSource();