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,
299 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
300 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)());
301 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
302 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
303 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
304 server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
305 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::recovery)());
306 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
307 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
308 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
309 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
310 server.expose(this, "", (int)(InternalEncryptionServer::getState)());
311 server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
312 server.expose(this, "", (std::string)(InternalEncryptionServer::getDevicePath)());
314 server.createNotification("InternalEncryptionServer::mount");
316 std::string source = findDevPath();
318 engine.reset(new INTERNAL_ENGINE(
319 source, INTERNAL_PATH,
320 ProgressBar([](int v) {
321 ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
322 std::to_string(v).c_str());
327 InternalEncryptionServer::~InternalEncryptionServer()
331 int InternalEncryptionServer::setMountPassword(const std::string& password)
333 return keyServer.get(engine->getSource(), password, mountKey);
336 int InternalEncryptionServer::mount()
338 if (mountKey.empty()) {
339 ERROR(SINK, "You need to call set_mount_password() first.");
340 return error::NoData;
343 BinaryData key = mountKey;
346 if (getState() != State::Encrypted) {
347 INFO(SINK, "Cannot mount, SD partition's state incorrect.");
348 return error::NoSuchDevice;
351 if (engine->isMounted()) {
352 INFO(SINK, "Partition already mounted.");
356 INFO(SINK, "Mounting internal storage.");
358 engine->mount(key, getOptions());
360 server.notify("InternalEncryptionServer::mount");
362 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
363 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
364 } catch (runtime::Exception &e) {
365 ERROR(SINK, "Mount failed: " + std::string(e.what()));
366 return error::Unknown;
372 int InternalEncryptionServer::umount()
374 if (getState() != State::Encrypted) {
375 ERROR(SINK, "Cannot umount, partition's state incorrect.");
376 return error::NoSuchDevice;
379 if (!engine->isMounted()) {
380 INFO(SINK, "Partition already umounted.");
384 INFO(SINK, "Closing all processes using internal storage.");
386 stopDependedSystemdUnits();
387 INFO(SINK, "Umounting internal storage.");
389 } catch (runtime::Exception &e) {
390 ERROR(SINK, "Umount failed: " + std::string(e.what()));
391 return error::Unknown;
397 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
399 if (getState() != State::Unencrypted) {
400 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
401 return error::NoSuchDevice;
404 BinaryData masterKey;
405 int ret = keyServer.get(engine->getSource(), password, masterKey);
406 if (ret != error::None)
409 auto encryptWorker = [masterKey, options, this]() {
411 showProgressUI("encrypt");
414 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
415 stopKnownSystemdUnits();
417 std::string source = engine->getSource();
418 auto mntPaths = findMountPointsByDevice(source);
420 if (!mntPaths.empty()) {
421 INFO(SINK, "Closing all processes using internal storage.");
422 stopDependedSystemdUnits();
424 INFO(SINK, "Unmounting internal storage.");
425 unmountInternalStorage(source);
428 INFO(SINK, "Encryption started.");
429 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
430 engine->encrypt(masterKey, options);
431 setOptions(options & getSupportedOptions());
433 INFO(SINK, "Encryption completed.");
434 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
435 server.notify("InternalEncryptionServer::mount");
437 INFO(SINK, "Syncing disk and rebooting.");
439 ::reboot(RB_AUTOBOOT);
440 } catch (runtime::Exception &e) {
441 ERROR(SINK, "Encryption failed: " + std::string(e.what()));
445 std::thread asyncWork(encryptWorker);
451 int InternalEncryptionServer::decrypt(const std::string& password)
453 if (getState() != State::Encrypted) {
454 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
455 return error::NoSuchDevice;
458 BinaryData masterKey;
459 int ret = keyServer.get(engine->getSource(), password, masterKey);
460 if (ret != error::None)
463 auto decryptWorker = [masterKey, this]() {
465 showProgressUI("decrypt");
468 if (engine->isMounted()) {
469 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
470 stopKnownSystemdUnits();
471 INFO(SINK, "Closing all processes using internal storage.");
472 stopDependedSystemdUnits();
474 INFO(SINK, "Umounting internal storage.");
479 } catch (runtime::Exception& e) {
480 stopDependedSystemdUnits();
485 INFO(SINK, "Decryption started.");
486 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
487 engine->decrypt(masterKey, getOptions());
489 INFO(SINK, "Decryption complete.");
490 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
492 INFO(SINK, "Syncing disk and rebooting.");
494 ::reboot(RB_AUTOBOOT);
495 } catch (runtime::Exception &e) {
496 ERROR(SINK, "Decryption failed: " + std::string(e.what()));
500 std::thread asyncWork(decryptWorker);
506 int InternalEncryptionServer::recovery()
508 int state = getState();
510 if (state == State::Unencrypted)
511 return error::NoSuchDevice;
513 if (state == State::CorruptedEncryption || state == State::CorruptedDecryption)
514 Ext4Tool::mkfs(engine->getSource());
517 fs.open("/opt/.factoryreset", std::ios::out);
522 dbus::Connection& systemDBus = dbus::Connection::getSystem();
523 systemDBus.methodcall("org.tizen.system.deviced",
524 "/Org/Tizen/System/DeviceD/Power",
525 "org.tizen.system.deviced.power",
527 -1, "()", "(si)", "reboot", 0);
528 } catch (runtime::Exception &e) {
529 ::reboot(RB_AUTOBOOT);
534 int InternalEncryptionServer::isPasswordInitialized()
536 return keyServer.isInitialized(engine->getSource());
539 int InternalEncryptionServer::initPassword(const std::string& password)
541 return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
544 int InternalEncryptionServer::cleanPassword(const std::string& password)
546 return keyServer.remove(engine->getSource(), password);
549 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
550 const std::string& newPassword)
552 return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
555 int InternalEncryptionServer::verifyPassword(const std::string& password)
557 return keyServer.verifyPassword(engine->getSource(), password);
560 int InternalEncryptionServer::getState()
562 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
564 throw runtime::Exception("Failed to get vconf value.");
567 std::string valueStr(value);
570 if (valueStr == "encrypted")
571 return State::Encrypted;
572 else if (valueStr == "unencrypted")
573 return State::Unencrypted;
574 else if (valueStr == "error_partially_encrypted")
575 return State::CorruptedEncryption;
576 else if (valueStr == "error_partially_decrypted")
577 return State::CorruptedDecryption;
579 return State::Invalid;
582 unsigned int InternalEncryptionServer::getSupportedOptions()
584 return engine->getSupportedOptions();
587 std::string InternalEncryptionServer::getDevicePath() const
589 return engine->getSource();