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 unit == "samsung-log-mgr.service") {
168 knownSystemdUnits.push_back(unit);
172 JobWatch watch(systemDBus);
174 for (const std::string& unit : knownSystemdUnits) {
175 INFO(SINK, "Stopping unit: " + unit);
176 const char* job = NULL;
177 systemDBus.methodcall("org.freedesktop.systemd1",
178 "/org/freedesktop/systemd1",
179 "org.freedesktop.systemd1.Manager",
181 -1, "(o)", "(ss)", unit.c_str(), "flush").get("(o)", &job);
182 INFO(SINK, "Waiting for job: " + std::string(job));
183 if (!watch.waitForJob(job))
184 throw runtime::Exception("Stopping unit: " + unit + " failed");
188 void stopDependedSystemdUnits()
190 dbus::Connection& systemDBus = dbus::Connection::getSystem();
191 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)
202 unitsToStop.insert(unit);
203 } catch (runtime::Exception &e) {
204 INFO(SINK, "Killing process: " + std::to_string(pid));
205 ::kill(pid, SIGKILL);
209 JobWatch watch(systemDBus);
211 for (const std::string& unit : unitsToStop) {
212 INFO(SINK, "Stopping unit: " + unit);
213 const char* job = NULL;
214 systemDBus.methodcall("org.freedesktop.systemd1",
216 "org.freedesktop.systemd1.Unit",
218 -1, "(o)", "(s)", "flush").get("(o)", &job);
219 INFO(SINK, "Waiting for job: " + std::string(job));
220 if (!watch.waitForJob(job))
221 throw runtime::Exception("Stopping unit: " + unit + " failed");
225 void showProgressUI(const std::string type)
227 dbus::Connection& systemDBus = dbus::Connection::getSystem();
228 std::string unit("ode-progress-ui@"+type+".service");
230 JobWatch watch(systemDBus);
231 INFO(SINK, "Start unit: " + unit);
233 const char* job = NULL;
234 systemDBus.methodcall("org.freedesktop.systemd1",
235 "/org/freedesktop/systemd1",
236 "org.freedesktop.systemd1.Manager",
238 -1, "(o)", "(ss)", unit.c_str(), "replace").get("(o)", &job);
240 INFO(SINK, "Waiting for job: " + std::string(job));
241 if (!watch.waitForJob(job))
242 throw runtime::Exception("Starting unit: " + unit + " failed");
245 unsigned int getOptions()
247 unsigned int result = 0;
251 ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
253 result |= InternalEncryption::Option::IncludeUnusedRegion;
259 void setOptions(unsigned int options)
263 if (options & InternalEncryption::Option::IncludeUnusedRegion) {
268 ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
271 void unmountInternalStorage(const std::string& source)
274 auto mntPaths = findMountPointsByDevice(source);
278 bool unmounted = true;
279 for(const auto& path : mntPaths) {
280 INFO(SINK, "Unmounting " + path);
281 if (::umount(path.c_str()) == -1) {
282 // If it's busy or was already unmounted ignore the error
283 if (errno != EBUSY && errno != EINVAL) {
284 throw runtime::Exception("umount() error: " + runtime::GetSystemErrorMessage());
290 stopDependedSystemdUnits();
296 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv,
301 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
302 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)());
303 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
304 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
305 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
306 server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
307 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::recovery)());
308 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
309 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
310 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
311 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
312 server.expose(this, "", (int)(InternalEncryptionServer::getState)());
313 server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
314 server.expose(this, "", (std::string)(InternalEncryptionServer::getDevicePath)());
316 server.createNotification("InternalEncryptionServer::mount");
318 std::string source = findDevPath();
320 engine.reset(new INTERNAL_ENGINE(
321 source, INTERNAL_PATH,
322 ProgressBar([](int v) {
323 ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
324 std::to_string(v).c_str());
329 InternalEncryptionServer::~InternalEncryptionServer()
333 int InternalEncryptionServer::setMountPassword(const std::string& password)
335 return keyServer.get(engine->getSource(), password, mountKey);
338 int InternalEncryptionServer::mount()
340 if (mountKey.empty()) {
341 ERROR(SINK, "You need to call set_mount_password() first.");
342 return error::NoData;
345 BinaryData key = mountKey;
348 if (getState() != State::Encrypted) {
349 INFO(SINK, "Cannot mount, SD partition's state incorrect.");
350 return error::NoSuchDevice;
353 if (engine->isMounted()) {
354 INFO(SINK, "Partition already mounted.");
358 INFO(SINK, "Mounting internal storage.");
360 engine->mount(key, getOptions());
362 server.notify("InternalEncryptionServer::mount");
364 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
365 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
366 } catch (runtime::Exception &e) {
367 ERROR(SINK, "Mount failed: " + std::string(e.what()));
368 return error::Unknown;
374 int InternalEncryptionServer::umount()
376 if (getState() != State::Encrypted) {
377 ERROR(SINK, "Cannot umount, partition's state incorrect.");
378 return error::NoSuchDevice;
381 if (!engine->isMounted()) {
382 INFO(SINK, "Partition already umounted.");
386 INFO(SINK, "Closing all processes using internal storage.");
388 stopDependedSystemdUnits();
389 INFO(SINK, "Umounting internal storage.");
391 } catch (runtime::Exception &e) {
392 ERROR(SINK, "Umount failed: " + std::string(e.what()));
393 return error::Unknown;
399 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
401 if (getState() != State::Unencrypted) {
402 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
403 return error::NoSuchDevice;
406 BinaryData masterKey;
407 int ret = keyServer.get(engine->getSource(), password, masterKey);
408 if (ret != error::None)
411 auto encryptWorker = [masterKey, options, this]() {
413 showProgressUI("encrypt");
416 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
417 stopKnownSystemdUnits();
419 std::string source = engine->getSource();
420 auto mntPaths = findMountPointsByDevice(source);
422 if (!mntPaths.empty()) {
423 INFO(SINK, "Closing all processes using internal storage.");
424 stopDependedSystemdUnits();
426 INFO(SINK, "Unmounting internal storage.");
427 unmountInternalStorage(source);
430 INFO(SINK, "Encryption started.");
431 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
432 engine->encrypt(masterKey, options);
433 setOptions(options & getSupportedOptions());
435 INFO(SINK, "Encryption completed.");
436 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
437 server.notify("InternalEncryptionServer::mount");
439 INFO(SINK, "Syncing disk and rebooting.");
441 ::reboot(RB_AUTOBOOT);
442 } catch (runtime::Exception &e) {
443 ERROR(SINK, "Encryption failed: " + std::string(e.what()));
447 std::thread asyncWork(encryptWorker);
453 int InternalEncryptionServer::decrypt(const std::string& password)
455 if (getState() != State::Encrypted) {
456 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
457 return error::NoSuchDevice;
460 BinaryData masterKey;
461 int ret = keyServer.get(engine->getSource(), password, masterKey);
462 if (ret != error::None)
465 auto decryptWorker = [masterKey, this]() {
467 showProgressUI("decrypt");
470 if (engine->isMounted()) {
471 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
472 stopKnownSystemdUnits();
473 INFO(SINK, "Closing all processes using internal storage.");
474 stopDependedSystemdUnits();
476 INFO(SINK, "Umounting internal storage.");
481 } catch (runtime::Exception& e) {
482 stopDependedSystemdUnits();
487 INFO(SINK, "Decryption started.");
488 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
489 engine->decrypt(masterKey, getOptions());
491 INFO(SINK, "Decryption complete.");
492 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
494 INFO(SINK, "Syncing disk and rebooting.");
496 ::reboot(RB_AUTOBOOT);
497 } catch (runtime::Exception &e) {
498 ERROR(SINK, "Decryption failed: " + std::string(e.what()));
502 std::thread asyncWork(decryptWorker);
508 int InternalEncryptionServer::recovery()
510 int state = getState();
512 if (state == State::Unencrypted)
513 return error::NoSuchDevice;
515 if (state == State::Corrupted)
516 Ext4Tool::mkfs(engine->getSource());
519 fs.open("/opt/.factoryreset", std::ios::out);
524 dbus::Connection& systemDBus = dbus::Connection::getSystem();
525 systemDBus.methodcall("org.tizen.system.deviced",
526 "/Org/Tizen/System/DeviceD/Power",
527 "org.tizen.system.deviced.power",
529 -1, "()", "(si)", "reboot", 0);
530 } catch (runtime::Exception &e) {
531 ::reboot(RB_AUTOBOOT);
536 int InternalEncryptionServer::isPasswordInitialized()
538 return keyServer.isInitialized(engine->getSource());
541 int InternalEncryptionServer::initPassword(const std::string& password)
543 return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
546 int InternalEncryptionServer::cleanPassword(const std::string& password)
548 return keyServer.remove(engine->getSource(), password);
551 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
552 const std::string& newPassword)
554 return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
557 int InternalEncryptionServer::verifyPassword(const std::string& password)
559 return keyServer.verifyPassword(engine->getSource(), password);
562 int InternalEncryptionServer::getState()
564 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
566 throw runtime::Exception("Failed to get vconf value.");
569 std::string valueStr(value);
572 if (valueStr == "encrypted")
573 return State::Encrypted;
574 else if (valueStr == "unencrypted")
575 return State::Unencrypted;
576 else if (valueStr == "error_partially_encrypted" || valueStr == "error_partially_decrypted")
577 return State::Corrupted;
579 return State::Invalid;
582 unsigned int InternalEncryptionServer::getSupportedOptions()
584 return engine->getSupportedOptions();
587 std::string InternalEncryptionServer::getDevicePath() const
589 return engine->getSource();