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 unit == "connman.socket") {
162 knownSystemdUnits.insert(knownSystemdUnits.begin(), unit);
163 } else if (unit.compare(0, 5, "user@") == 0 ||
164 unit == "tlm.service" ||
165 unit == "resourced.service" ||
166 unit == "security-manager.service") {
167 knownSystemdUnits.push_back(unit);
171 JobWatch watch(systemDBus);
173 for (const std::string& unit : knownSystemdUnits) {
174 INFO(SINK, "Stopping unit: " + unit);
175 const char* job = NULL;
176 systemDBus.methodcall("org.freedesktop.systemd1",
177 "/org/freedesktop/systemd1",
178 "org.freedesktop.systemd1.Manager",
180 -1, "(o)", "(ss)", unit.c_str(), "flush").get("(o)", &job);
181 INFO(SINK, "Waiting for job: " + std::string(job));
182 if (!watch.waitForJob(job))
183 throw runtime::Exception("Stopping unit: " + unit + " failed");
187 void stopDependedSystemdUnits()
189 dbus::Connection& systemDBus = dbus::Connection::getSystem();
190 std::set<std::string> unitsToStop;
193 for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
196 systemDBus.methodcall("org.freedesktop.systemd1",
197 "/org/freedesktop/systemd1",
198 "org.freedesktop.systemd1.Manager",
200 -1, "(o)", "(u)", (unsigned int)pid)
203 if (std::string(unit) ==
204 "/org/freedesktop/systemd1/unit/samsung_2dlog_2dmgr_2eservice")
207 unitsToStop.insert(unit);
208 } catch (runtime::Exception &e) {
209 INFO(SINK, "Killing process: " + std::to_string(pid));
210 ::kill(pid, SIGKILL);
214 JobWatch watch(systemDBus);
216 for (const std::string& unit : unitsToStop) {
217 INFO(SINK, "Stopping unit: " + unit);
218 const char* job = NULL;
219 systemDBus.methodcall("org.freedesktop.systemd1",
221 "org.freedesktop.systemd1.Unit",
223 -1, "(o)", "(s)", "flush").get("(o)", &job);
224 INFO(SINK, "Waiting for job: " + std::string(job));
225 if (!watch.waitForJob(job))
226 throw runtime::Exception("Stopping unit: " + unit + " failed");
229 if (::umount2("/sys/fs/cgroup", MNT_FORCE | MNT_DETACH) != 0)
230 INFO(SINK, "Failed to unmount cgroup");
236 void showProgressUI(const std::string type)
238 dbus::Connection& systemDBus = dbus::Connection::getSystem();
239 std::string unit("ode-progress-ui@"+type+".service");
241 JobWatch watch(systemDBus);
242 INFO(SINK, "Start unit: " + unit);
244 const char* job = NULL;
245 systemDBus.methodcall("org.freedesktop.systemd1",
246 "/org/freedesktop/systemd1",
247 "org.freedesktop.systemd1.Manager",
249 -1, "(o)", "(ss)", unit.c_str(), "replace").get("(o)", &job);
251 INFO(SINK, "Waiting for job: " + std::string(job));
252 if (!watch.waitForJob(job))
253 throw runtime::Exception("Starting unit: " + unit + " failed");
256 unsigned int getOptions()
258 unsigned int result = 0;
262 ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
264 result |= InternalEncryption::Option::IncludeUnusedRegion;
270 void setOptions(unsigned int options)
274 if (options & InternalEncryption::Option::IncludeUnusedRegion) {
279 ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
282 void unmountInternalStorage(const std::string& source)
285 auto mntPaths = findMountPointsByDevice(source);
289 bool unmounted = true;
290 for(const auto& path : mntPaths) {
291 INFO(SINK, "Unmounting " + path);
292 if (::umount(path.c_str()) == -1) {
293 // If it's busy or was already unmounted ignore the error
294 if (errno != EBUSY && errno != EINVAL) {
295 throw runtime::Exception("umount() error: " + runtime::GetSystemErrorMessage());
301 stopDependedSystemdUnits();
307 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv,
312 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
313 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)(std::vector<unsigned char>, unsigned int));
314 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
315 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
316 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
317 server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
318 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::recovery)());
319 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
320 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
321 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
322 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
323 server.expose(this, "", (int)(InternalEncryptionServer::getState)());
324 server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
325 server.expose(this, "", (std::string)(InternalEncryptionServer::getDevicePath)());
327 server.createNotification("InternalEncryptionServer::mount");
329 std::string source = findDevPath();
331 engine.reset(new INTERNAL_ENGINE(
332 source, INTERNAL_PATH,
333 ProgressBar([](int v) {
334 ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
335 std::to_string(v).c_str());
340 InternalEncryptionServer::~InternalEncryptionServer()
344 int InternalEncryptionServer::setMountPassword(const std::string& password)
346 return keyServer.get(engine->getSource(), password, mountKey);
349 int InternalEncryptionServer::mount(const std::vector<unsigned char> &mk, unsigned int options)
351 if (mountKey.empty() && mk.empty()) {
352 ERROR(SINK, "You need to set master key first.");
353 return error::NoData;
356 BinaryData key = mk.empty() ? mountKey : mk;
359 if (getState() != State::Encrypted) {
360 INFO(SINK, "Cannot mount, SD partition's state incorrect.");
361 return error::NoSuchDevice;
364 if (engine->isMounted()) {
365 INFO(SINK, "Partition already mounted.");
369 INFO(SINK, "Mounting internal storage.");
371 engine->mount(key, getOptions());
373 server.notify("InternalEncryptionServer::mount");
375 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
376 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
377 } catch (runtime::Exception &e) {
378 ERROR(SINK, "Mount failed: " + std::string(e.what()));
379 return error::Unknown;
385 int InternalEncryptionServer::umount()
387 if (getState() != State::Encrypted) {
388 ERROR(SINK, "Cannot umount, partition's state incorrect.");
389 return error::NoSuchDevice;
392 if (!engine->isMounted()) {
393 INFO(SINK, "Partition already umounted.");
397 INFO(SINK, "Closing all processes using internal storage.");
399 stopDependedSystemdUnits();
400 INFO(SINK, "Umounting internal storage.");
402 } catch (runtime::Exception &e) {
403 ERROR(SINK, "Umount failed: " + std::string(e.what()));
404 return error::Unknown;
410 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
412 if (getState() != State::Unencrypted) {
413 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
414 return error::NoSuchDevice;
417 BinaryData masterKey;
418 int ret = keyServer.get(engine->getSource(), password, masterKey);
419 if (ret != error::None)
422 auto encryptWorker = [masterKey, options, this]() {
424 showProgressUI("encrypt");
427 runtime::File file("/opt/etc/.odeprogress");
430 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
431 stopKnownSystemdUnits();
433 std::string source = engine->getSource();
434 auto mntPaths = findMountPointsByDevice(source);
436 if (!mntPaths.empty()) {
437 INFO(SINK, "Closing all processes using internal storage.");
438 stopDependedSystemdUnits();
440 INFO(SINK, "Unmounting internal storage.");
441 unmountInternalStorage(source);
444 INFO(SINK, "Encryption started.");
445 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
446 engine->encrypt(masterKey, options);
447 setOptions(options & getSupportedOptions());
449 INFO(SINK, "Encryption completed.");
450 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
451 server.notify("InternalEncryptionServer::mount");
455 INFO(SINK, "Syncing disk and rebooting.");
457 ::reboot(RB_AUTOBOOT);
458 } catch (runtime::Exception &e) {
459 ERROR(SINK, "Encryption failed: " + std::string(e.what()));
463 std::thread asyncWork(encryptWorker);
469 int InternalEncryptionServer::decrypt(const std::string& password)
471 if (getState() != State::Encrypted) {
472 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
473 return error::NoSuchDevice;
476 BinaryData masterKey;
477 int ret = keyServer.get(engine->getSource(), password, masterKey);
478 if (ret != error::None)
481 auto decryptWorker = [masterKey, this]() {
483 showProgressUI("decrypt");
486 runtime::File file("/opt/etc/.odeprogress");
489 if (engine->isMounted()) {
490 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
491 stopKnownSystemdUnits();
492 INFO(SINK, "Closing all processes using internal storage.");
493 stopDependedSystemdUnits();
495 INFO(SINK, "Umounting internal storage.");
500 } catch (runtime::Exception& e) {
501 stopDependedSystemdUnits();
506 INFO(SINK, "Decryption started.");
507 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
508 engine->decrypt(masterKey, getOptions());
510 INFO(SINK, "Decryption complete.");
511 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
515 INFO(SINK, "Syncing disk and rebooting.");
517 ::reboot(RB_AUTOBOOT);
518 } catch (runtime::Exception &e) {
519 ERROR(SINK, "Decryption failed: " + std::string(e.what()));
523 std::thread asyncWork(decryptWorker);
529 int InternalEncryptionServer::recovery()
531 int state = getState();
533 if (state == State::Unencrypted)
534 return error::NoSuchDevice;
536 runtime::File file("/opt/.factoryreset");
541 dbus::Connection& systemDBus = dbus::Connection::getSystem();
542 systemDBus.methodcall("org.tizen.system.deviced",
543 "/Org/Tizen/System/DeviceD/Power",
544 "org.tizen.system.deviced.power",
546 -1, "()", "(si)", "reboot", 0);
547 } catch (runtime::Exception &e) {
548 ::reboot(RB_AUTOBOOT);
553 int InternalEncryptionServer::isPasswordInitialized()
555 return keyServer.isInitialized(engine->getSource());
558 int InternalEncryptionServer::initPassword(const std::string& password)
560 return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
563 int InternalEncryptionServer::cleanPassword(const std::string& password)
565 return keyServer.remove(engine->getSource(), password);
568 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
569 const std::string& newPassword)
571 return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
574 int InternalEncryptionServer::verifyPassword(const std::string& password)
576 return keyServer.verifyPassword(engine->getSource(), password);
579 int InternalEncryptionServer::getState()
581 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
583 throw runtime::Exception("Failed to get vconf value.");
586 std::string valueStr(value);
589 if (valueStr == "encrypted")
590 return State::Encrypted;
591 else if (valueStr == "unencrypted")
592 return State::Unencrypted;
593 else if (valueStr == "error_partially_encrypted" || valueStr == "error_partially_decrypted")
594 return State::Corrupted;
596 return State::Invalid;
599 unsigned int InternalEncryptionServer::getSupportedOptions()
601 return engine->getSupportedOptions();
604 std::string InternalEncryptionServer::getDevicePath() const
606 return engine->getSource();