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>
26 #include <sys/mount.h>
27 #include <sys/reboot.h>
33 #include <tzplatform_config.h>
34 #include <klay/process.h>
35 #include <klay/file-user.h>
36 #include <klay/filesystem.h>
37 #include <klay/dbus/connection.h>
38 #include <klay/error.h>
42 #include "progress-bar.h"
43 #include "rmi/common.h"
45 #include "internal-encryption.h"
46 #include "internal-encryption-common.h"
52 const char *PRIVILEGE_PLATFORM = "http://tizen.org/privilege/internal/default/platform";
54 // TODO: see recovery()
55 const std::string PROG_FACTORY_RESET = "/usr/bin/dbus-send";
56 const std::vector<std::string> wipeCommand = {
61 "--dest=com.samsung.factoryreset",
62 "/com/samsung/factoryreset",
63 "com.samsung.factoryreset.start.setting"
67 // watches systemd jobs
70 explicit JobWatch(dbus::Connection& systemDBus);
73 bool waitForJob(const std::string& job);
76 void jobRemoved(const dbus::Variant& parameters);
80 const std::string& job,
81 const std::string& unit,
82 const std::string& result) : id(id), job(job), unit(unit), result(result) {}
89 dbus::Connection::SubscriptionId id;
90 dbus::Connection& systemDBus;
91 std::list<Job> removedJobs;
93 std::condition_variable jobsCv;
96 JobWatch::JobWatch(dbus::Connection& systemDBus) : systemDBus(systemDBus) {
97 auto callback = [this](dbus::Variant parameters) {
98 this->jobRemoved(parameters);
101 id = systemDBus.subscribeSignal("",
102 "/org/freedesktop/systemd1",
103 "org.freedesktop.systemd1.Manager",
108 JobWatch::~JobWatch() {
109 systemDBus.unsubscribeSignal(id);
112 bool JobWatch::waitForJob(const std::string& job) {
114 std::unique_lock<std::mutex> lock(jobsMutex);
115 jobsCv.wait(lock, [this]{ return !removedJobs.empty(); });
117 while(!removedJobs.empty()) {
118 bool match = (removedJobs.front().job == job);
119 bool done = (removedJobs.front().result == "done");
120 removedJobs.pop_front();
127 void JobWatch::jobRemoved(const dbus::Variant& parameters)
133 parameters.get("(uoss)", &id, &job, &unit, &result);
134 INFO(SINK, "id:" + std::to_string(id) + " job:" + job + " unit:" + unit + " result:" + result);
137 std::lock_guard<std::mutex> guard(jobsMutex);
138 removedJobs.emplace_back(id, job, unit, result);
143 void stopKnownSystemdUnits()
145 std::vector<std::string> knownSystemdUnits;
146 dbus::Connection& systemDBus = dbus::Connection::getSystem();
147 dbus::VariantIterator iter;
149 systemDBus.methodcall("org.freedesktop.systemd1",
150 "/org/freedesktop/systemd1",
151 "org.freedesktop.systemd1.Manager",
153 -1, "(a(ssssssouso))", "")
154 .get("(a(ssssssouso))", &iter);
157 unsigned int dataUint;
161 ret = iter.get("(ssssssouso)", dataStr, dataStr + 1, dataStr + 2,
162 dataStr + 3, dataStr + 4, dataStr + 5,
163 dataStr + 6, &dataUint, dataStr + 7,
170 std::string unit(dataStr[0]);
171 if (unit == "security-manager.socket") {
172 knownSystemdUnits.insert(knownSystemdUnits.begin(), unit);
173 } else if (unit.compare(0, 5, "user@") == 0 ||
174 unit == "tlm.service" ||
175 unit == "resourced.service" ||
176 unit == "security-manager.service") {
177 knownSystemdUnits.push_back(unit);
181 JobWatch watch(systemDBus);
183 for (const std::string& unit : knownSystemdUnits) {
184 INFO(SINK, "Stopping unit: " + unit);
185 const char* job = NULL;
186 systemDBus.methodcall("org.freedesktop.systemd1",
187 "/org/freedesktop/systemd1",
188 "org.freedesktop.systemd1.Manager",
190 -1, "(o)", "(ss)", unit.c_str(), "flush").get("(o)", &job);
191 INFO(SINK, "Waiting for job: " + std::string(job));
192 if (!watch.waitForJob(job))
193 throw runtime::Exception("Stopping unit: " + unit + " failed");
197 void stopDependedSystemdUnits()
199 dbus::Connection& systemDBus = dbus::Connection::getSystem();
200 std::set<std::string> unitsToStop;
202 for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
205 systemDBus.methodcall("org.freedesktop.systemd1",
206 "/org/freedesktop/systemd1",
207 "org.freedesktop.systemd1.Manager",
209 -1, "(o)", "(u)", (unsigned int)pid)
211 unitsToStop.insert(unit);
212 } catch (runtime::Exception &e) {
213 INFO(SINK, "Killing process: " + std::to_string(pid));
214 ::kill(pid, SIGKILL);
218 JobWatch watch(systemDBus);
220 for (const std::string& unit : unitsToStop) {
221 INFO(SINK, "Stopping unit: " + unit);
222 const char* job = NULL;
223 systemDBus.methodcall("org.freedesktop.systemd1",
225 "org.freedesktop.systemd1.Unit",
227 -1, "(o)", "(s)", "flush").get("(o)", &job);
228 INFO(SINK, "Waiting for job: " + std::string(job));
229 if (!watch.waitForJob(job))
230 throw runtime::Exception("Stopping unit: " + unit + " failed");
234 void showProgressUI(const std::string type)
236 dbus::Connection& systemDBus = dbus::Connection::getSystem();
237 std::string unit("ode-progress-ui@"+type+".service");
239 JobWatch watch(systemDBus);
240 INFO(SINK, "Start unit: " + unit);
242 const char* job = NULL;
243 systemDBus.methodcall("org.freedesktop.systemd1",
244 "/org/freedesktop/systemd1",
245 "org.freedesktop.systemd1.Manager",
247 -1, "(o)", "(ss)", unit.c_str(), "replace").get("(o)", &job);
249 INFO(SINK, "Waiting for job: " + std::string(job));
250 if (!watch.waitForJob(job))
251 throw runtime::Exception("Starting unit: " + unit + " failed");
254 unsigned int getOptions()
256 unsigned int result = 0;
260 ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
262 result |= InternalEncryption::Option::IncludeUnusedRegion;
268 void setOptions(unsigned int options)
272 if (options & InternalEncryption::Option::IncludeUnusedRegion) {
277 ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
280 void unmountInternalStorage(const std::string& source)
283 auto mntPaths = findMountPointsByDevice(source);
287 bool unmounted = true;
288 for(const auto& path : mntPaths) {
289 INFO(SINK, "Unmounting " + path);
290 if (::umount(path.c_str()) == -1) {
291 // If it's busy or was already unmounted ignore the error
292 if (errno != EBUSY && errno != EINVAL) {
293 throw runtime::Exception("umount() error: " + runtime::GetSystemErrorMessage());
299 stopDependedSystemdUnits();
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)());
312 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
313 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
314 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
315 server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
316 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
317 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
318 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
319 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
320 server.expose(this, "", (int)(InternalEncryptionServer::getState)());
321 server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
322 server.expose(this, "", (std::string)(InternalEncryptionServer::getDevicePath)());
324 server.createNotification("InternalEncryptionServer::mount");
326 std::string source = findDevPath();
328 engine.reset(new INTERNAL_ENGINE(
329 source, INTERNAL_PATH,
330 ProgressBar([](int v) {
331 ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
332 std::to_string(v).c_str());
337 InternalEncryptionServer::~InternalEncryptionServer()
341 int InternalEncryptionServer::setMountPassword(const std::string& password)
343 return keyServer.get(engine->getSource(), password, mountKey);
346 int InternalEncryptionServer::mount()
348 if (mountKey.empty()) {
349 ERROR(SINK, "You need to call set_mount_password() first.");
350 return error::NoData;
353 BinaryData key = mountKey;
356 if (getState() != State::Encrypted) {
357 INFO(SINK, "Cannot mount, SD partition's state incorrect.");
358 return error::NoSuchDevice;
361 if (engine->isMounted()) {
362 INFO(SINK, "Partition already mounted.");
366 INFO(SINK, "Mounting internal storage.");
368 engine->mount(key, getOptions());
370 server.notify("InternalEncryptionServer::mount");
372 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
373 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
374 } catch (runtime::Exception &e) {
375 ERROR(SINK, "Mount failed: " + std::string(e.what()));
376 return error::Unknown;
382 int InternalEncryptionServer::umount()
384 if (getState() != State::Encrypted) {
385 ERROR(SINK, "Cannot umount, partition's state incorrect.");
386 return error::NoSuchDevice;
389 if (!engine->isMounted()) {
390 INFO(SINK, "Partition already umounted.");
394 INFO(SINK, "Closing all processes using internal storage.");
396 stopDependedSystemdUnits();
397 INFO(SINK, "Umounting internal storage.");
399 } catch (runtime::Exception &e) {
400 ERROR(SINK, "Umount failed: " + std::string(e.what()));
401 return error::Unknown;
407 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
409 if (getState() != State::Unencrypted) {
410 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
411 return error::NoSuchDevice;
414 BinaryData masterKey;
415 int ret = keyServer.get(engine->getSource(), password, masterKey);
416 if (ret != error::None)
419 auto encryptWorker = [masterKey, options, this]() {
421 showProgressUI("Encrypting");
424 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
425 stopKnownSystemdUnits();
427 std::string source = engine->getSource();
428 auto mntPaths = findMountPointsByDevice(source);
430 if (!mntPaths.empty()) {
431 INFO(SINK, "Closing all processes using internal storage.");
432 stopDependedSystemdUnits();
434 INFO(SINK, "Unmounting internal storage.");
435 unmountInternalStorage(source);
438 INFO(SINK, "Encryption started.");
439 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
440 engine->encrypt(masterKey, options);
441 setOptions(options & getSupportedOptions());
443 INFO(SINK, "Encryption completed.");
444 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
445 server.notify("InternalEncryptionServer::mount");
447 INFO(SINK, "Syncing disk and rebooting.");
449 ::reboot(RB_AUTOBOOT);
450 } catch (runtime::Exception &e) {
451 ERROR(SINK, "Encryption failed: " + std::string(e.what()));
455 std::thread asyncWork(encryptWorker);
461 int InternalEncryptionServer::decrypt(const std::string& password)
463 if (getState() != State::Encrypted) {
464 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
465 return error::NoSuchDevice;
468 BinaryData masterKey;
469 int ret = keyServer.get(engine->getSource(), password, masterKey);
470 if (ret != error::None)
473 auto decryptWorker = [masterKey, this]() {
475 showProgressUI("Decrypting");
478 if (engine->isMounted()) {
479 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
480 stopKnownSystemdUnits();
481 INFO(SINK, "Closing all processes using internal storage.");
482 stopDependedSystemdUnits();
484 INFO(SINK, "Umounting internal storage.");
489 } catch (runtime::Exception& e) {
490 stopDependedSystemdUnits();
495 INFO(SINK, "Decryption started.");
496 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
497 engine->decrypt(masterKey, getOptions());
499 INFO(SINK, "Decryption complete.");
500 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
502 INFO(SINK, "Syncing disk and rebooting.");
504 ::reboot(RB_AUTOBOOT);
505 } catch (runtime::Exception &e) {
506 ERROR(SINK, "Decryption failed: " + std::string(e.what()));
510 std::thread asyncWork(decryptWorker);
516 int InternalEncryptionServer::recovery()
518 if (getState() == State::Unencrypted) {
519 return error::NoSuchDevice;
523 runtime::Process proc(PROG_FACTORY_RESET, wipeCommand);
524 if (proc.execute() == -1) {
525 ERROR(SINK, "Failed to launch factory-reset");
526 return error::WrongPassword;
532 int InternalEncryptionServer::isPasswordInitialized()
534 return keyServer.isInitialized(engine->getSource());
537 int InternalEncryptionServer::initPassword(const std::string& password)
539 return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
542 int InternalEncryptionServer::cleanPassword(const std::string& password)
544 return keyServer.remove(engine->getSource(), password);
547 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
548 const std::string& newPassword)
550 return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
553 int InternalEncryptionServer::verifyPassword(const std::string& password)
555 return keyServer.verifyPassword(engine->getSource(), password);
558 int InternalEncryptionServer::getState()
560 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
562 throw runtime::Exception("Failed to get vconf value.");
565 std::string valueStr(value);
568 if (valueStr == "encrypted") {
569 return State::Encrypted;
570 } else if (valueStr == "unencrypted") {
571 return State::Unencrypted;
573 return State::Corrupted;
577 unsigned int InternalEncryptionServer::getSupportedOptions()
579 return engine->getSupportedOptions();
582 std::string InternalEncryptionServer::getDevicePath() const
584 return engine->getSource();