2 * Copyright (c) 2015 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
22 #include <sys/mount.h>
23 #include <sys/reboot.h>
30 #include <tzplatform_config.h>
31 #include <klay/process.h>
32 #include <klay/file-user.h>
33 #include <klay/filesystem.h>
34 #include <klay/dbus/connection.h>
38 #include "progress-bar.h"
39 #include "engine/encryption/dmcrypt-engine.h"
40 #include "key-manager/key-manager.h"
42 #include "rmi/internal-encryption.h"
44 #define INTERNAL_ENGINE DMCryptEngine
45 #define INTERNAL_DEV_PATH "/dev/disk/by-partlabel"
46 #define INTERNAL_DEV_NAME "USER"
47 #define INTERNAL_PATH "/opt/usr"
48 #define INTERNAL_STATE_VCONF_KEY VCONFKEY_ODE_CRYPTO_STATE
49 #define INTERNAL_OPTION_ONLY_USED_REGION_VCONF_KEY VCONFKEY_ODE_FAST_ENCRYPTION
51 #define PRIVILEGE_PLATFORM "http://tizen.org/privilege/internal/default/platform"
53 const std::string PROG_FACTORY_RESET = "/usr/bin/dbus-send";
54 const std::vector<std::string> wipeCommand = {
59 "--dest=com.samsung.factoryreset",
60 "/com/samsung/factoryreset",
61 "com.samsung.factoryreset.start.setting"
68 std::string findDevPath()
70 std::string source = INTERNAL_DEV_PATH "/" INTERNAL_DEV_NAME;
72 runtime::DirectoryIterator iter(INTERNAL_DEV_PATH), end;
75 const std::string& path = (*iter).getPath();
76 std::string name = path.substr(path.rfind('/') + 1);
78 upper.reserve(name.size());
80 upper += std::toupper(c);
82 if (upper == INTERNAL_DEV_NAME) {
88 } catch (runtime::Exception &e) {}
90 char *dev = ::realpath(source.c_str(), NULL);
92 throw runtime::Exception("Failed to find device path.");
95 std::string devPath(dev);
101 std::string findMntPath(const std::string &devPath)
105 FILE* mtab = ::setmntent("/etc/mtab", "r");
106 struct mntent* entry = NULL;
107 while ((entry = ::getmntent(mtab)) != NULL) {
108 if (devPath == entry->mnt_fsname) {
109 ret = entry->mnt_dir;
118 std::unique_ptr<INTERNAL_ENGINE> engine;
119 KeyManager::data mountKey;
121 void stopKnownSystemdServices() {
122 std::vector<std::string> knownSystemdServices;
123 dbus::Connection& systemDBus = dbus::Connection::getSystem();
124 dbus::VariantIterator iter;
126 systemDBus.methodcall("org.freedesktop.systemd1",
127 "/org/freedesktop/systemd1",
128 "org.freedesktop.systemd1.Manager",
130 -1, "(a(ssssssouso))", "")
131 .get("(a(ssssssouso))", &iter);
134 unsigned int dataUint;
138 ret = iter.get("(ssssssouso)", dataStr, dataStr + 1, dataStr + 2,
139 dataStr + 3, dataStr + 4, dataStr + 5,
140 dataStr + 6, &dataUint, dataStr + 7,
147 std::string service(dataStr[0]);
148 if (service.compare(0, 5, "user@") == 0 ||
149 service == "tlm.service" ||
150 service == "resourced.service") {
151 knownSystemdServices.push_back(service);
155 for (const std::string& service : knownSystemdServices) {
156 INFO(SINK, "Stop service - " + service);
157 systemDBus.methodcall("org.freedesktop.systemd1",
158 "/org/freedesktop/systemd1",
159 "org.freedesktop.systemd1.Manager",
161 -1, "", "(ss)", service.c_str(), "flush");
167 void stopDependedSystemdServices()
169 dbus::Connection& systemDBus = dbus::Connection::getSystem();
170 std::set<std::string> servicesToStop;
172 for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
175 systemDBus.methodcall("org.freedesktop.systemd1",
176 "/org/freedesktop/systemd1",
177 "org.freedesktop.systemd1.Manager",
179 -1, "(o)", "(u)", (unsigned int)pid)
180 .get("(o)", &service);
181 servicesToStop.insert(service);
182 } catch (runtime::Exception &e) {
183 INFO(SINK, "Close process - " + std::to_string(pid));
184 ::kill(pid, SIGKILL);
188 for (const std::string& service : servicesToStop) {
189 INFO(SINK, "Close service - " + service);
190 systemDBus.methodcall("org.freedesktop.systemd1",
192 "org.freedesktop.systemd1.Unit",
194 -1, "", "(s)", "flush");
198 void showProgressUI(const std::string type) {
199 ::tzplatform_set_user(::tzplatform_getuid(TZ_SYS_DEFAULT_USER));
200 std::string defaultUserHome(::tzplatform_getenv(TZ_USER_HOME));
201 ::tzplatform_reset_user();
204 runtime::File shareDirectory("/opt/home/root/share");
205 if (!shareDirectory.exists()) {
206 shareDirectory.makeDirectory(true);
209 runtime::File elmConfigDir(shareDirectory.getPath() + "/.elementary");
210 if (!elmConfigDir.exists()) {
211 runtime::File defaultElmConfigDir(defaultUserHome + "/share/.elementary");
212 defaultElmConfigDir.copyTo(shareDirectory.getPath());
214 } catch (runtime::Exception &e) {
215 ERROR(SINK, "Failed to set up elm configuration");
218 std::vector<std::string> args = {
219 "ode", "progress", type, "Internal"
222 runtime::Process proc("/usr/bin/ode", args);
226 unsigned int getOptions()
228 unsigned int result = 0;
232 ::vconf_get_bool(INTERNAL_OPTION_ONLY_USED_REGION_VCONF_KEY, &value);
234 result |= InternalEncryption::Option::IncludeUnusedRegion;
240 void setOptions(unsigned int options)
244 if (options & InternalEncryption::Option::IncludeUnusedRegion) {
249 ::vconf_set_bool(INTERNAL_OPTION_ONLY_USED_REGION_VCONF_KEY, value);
254 InternalEncryption::InternalEncryption(ODEControlContext& ctx) :
257 context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::setMountPassword)(std::string));
258 context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::mount)());
259 context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::umount)());
260 context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::encrypt)(std::string, unsigned int));
261 context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::decrypt)(std::string));
262 context.expose(this, "", (int)(InternalEncryption::isPasswordInitialized)());
263 context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::initPassword)(std::string));
264 context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::cleanPassword)(std::string));
265 context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::changePassword)(std::string, std::string));
266 context.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryption::verifyPassword)(std::string));
267 context.expose(this, "", (int)(InternalEncryption::getState)());
268 context.expose(this, "", (unsigned int)(InternalEncryption::getSupportedOptions)());
270 context.createNotification("InternalEncryption::mount");
272 std::string source = findDevPath();
274 engine.reset(new INTERNAL_ENGINE(
275 source, INTERNAL_PATH,
276 ProgressBar([](int v) {
277 ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
278 std::to_string(v).c_str());
283 InternalEncryption::~InternalEncryption()
287 int InternalEncryption::setMountPassword(const std::string& password)
289 KeyManager::data pwData(password.begin(), password.end());
290 KeyManager keyManager(engine->getKeyMeta());
291 if (!keyManager.verifyPassword(pwData)) {
295 ode::mountKey = keyManager.getMasterKey(pwData);
300 int InternalEncryption::mount()
302 if (getState() != State::Encrypted) {
306 if (engine->isMounted()) {
307 INFO(SINK, "Already mounted");
312 INFO(SINK, "Mount internal storage...");
313 engine->mount(mountKey, getOptions());
316 context.notify("InternalEncryption::mount");
318 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
319 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
320 } catch (runtime::Exception &e) {
321 ERROR(SINK, "Mount failed - " + std::string(e.what()));
328 int InternalEncryption::umount()
330 if (getState() != State::Encrypted) {
334 if (!engine->isMounted()) {
335 INFO(SINK, "Already umounted");
340 INFO(SINK, "Close all processes using internal storage...");
341 stopDependedSystemdServices();
342 INFO(SINK, "Umount internal storage...");
344 } catch (runtime::Exception &e) {
345 ERROR(SINK, "Umount failed - " + std::string(e.what()));
352 int InternalEncryption::encrypt(const std::string& password, unsigned int options)
354 if (getState() != State::Unencrypted) {
358 KeyManager::data pwData(password.begin(), password.end());
359 KeyManager keyManager(engine->getKeyMeta());
361 if (!keyManager.verifyPassword(pwData)) {
365 KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
366 auto encryptWorker = [MasterKey, options, this]() {
368 std::string source = engine->getSource();
369 std::string mntPath = findMntPath(source);
371 if (!mntPath.empty()) {
372 INFO(SINK, "Close all known systemd services that might be using internal storage...");
373 stopKnownSystemdServices();
374 INFO(SINK, "Close all processes using internal storage...");
375 stopDependedSystemdServices();
378 while (!mntPath.empty()) {
379 INFO(SINK, "Umount internal storage...");
380 while (::umount(mntPath.c_str()) == -1) {
381 if (errno != EBUSY) {
382 throw runtime::Exception("Umount error - " + std::to_string(errno));
384 stopDependedSystemdServices();
386 mntPath = findMntPath(source);
389 showProgressUI("Encrypting");
391 INFO(SINK, "Encryption started...");
392 engine->encrypt(MasterKey, options);
393 setOptions(options & getSupportedOptions());
395 INFO(SINK, "Encryption completed");
396 ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "encrypted");
397 context.notify("InternalEncryption::mount");
399 INFO(SINK, "Syncing disk and rebooting...");
401 ::reboot(RB_AUTOBOOT);
402 } catch (runtime::Exception &e) {
403 ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "error_partially_encrypted");
404 ERROR(SINK, "Encryption failed - " + std::string(e.what()));
408 std::thread asyncWork(encryptWorker);
414 int InternalEncryption::decrypt(const std::string& password)
416 if (getState() != State::Encrypted) {
420 KeyManager::data pwData(password.begin(), password.end());
421 KeyManager keyManager(engine->getKeyMeta());
423 if (!keyManager.verifyPassword(pwData)) {
427 KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
428 auto decryptWorker = [MasterKey, this]() {
430 if (engine->isMounted()) {
431 INFO(SINK, "Close all known systemd services that might be using internal storage...");
432 stopKnownSystemdServices();
433 INFO(SINK, "Close all processes using internal storage...");
434 stopDependedSystemdServices();
436 INFO(SINK, "Umount internal storage...");
441 } catch (runtime::Exception& e) {
442 stopDependedSystemdServices();
447 showProgressUI("Decrypting");
449 INFO(SINK, "Decryption started...");
450 engine->decrypt(MasterKey, getOptions());
452 INFO(SINK, "Decryption completed");
453 ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "unencrypted");
455 INFO(SINK, "Syncing disk and rebooting...");
457 ::reboot(RB_AUTOBOOT);
458 } catch (runtime::Exception &e) {
459 ::vconf_set_str(INTERNAL_STATE_VCONF_KEY, "error_partially_encrypted");
460 ERROR(SINK, "Decryption failed - " + std::string(e.what()));
464 std::thread asyncWork(decryptWorker);
470 int InternalEncryption::recovery()
472 if (getState() != State::Unencrypted) {
477 runtime::Process proc(PROG_FACTORY_RESET, wipeCommand);
478 if (proc.execute() == -1) {
479 ERROR(SINK, "Failed to launch factory-reset");
486 int InternalEncryption::isPasswordInitialized()
488 if (engine->isKeyMetaSet()) {
494 int InternalEncryption::initPassword(const std::string& password)
496 KeyManager::data pwData(password.begin(), password.end());
497 KeyManager keyManager;
499 keyManager.initPassword(pwData);
500 engine->setKeyMeta(keyManager.serialize());
504 int InternalEncryption::cleanPassword(const std::string& password)
506 KeyManager::data pwData(password.begin(), password.end());
507 KeyManager keyManager(engine->getKeyMeta());
509 if (!keyManager.verifyPassword(pwData)) {
513 engine->clearKeyMeta();
517 int InternalEncryption::changePassword(const std::string& oldPassword,
518 const std::string& newPassword)
520 KeyManager::data oldPwData(oldPassword.begin(), oldPassword.end());
521 KeyManager::data newPwData(newPassword.begin(), newPassword.end());
522 KeyManager keyManager(engine->getKeyMeta());
524 if (!keyManager.verifyPassword(oldPwData)) {
528 keyManager.changePassword(oldPwData, newPwData);
529 engine->setKeyMeta(keyManager.serialize());
534 int InternalEncryption::verifyPassword(const std::string& password)
536 KeyManager::data pwData(password.begin(), password.end());
537 KeyManager keyManager(engine->getKeyMeta());
539 if (keyManager.verifyPassword(pwData)) {
545 int InternalEncryption::getState()
547 char *value = ::vconf_get_str(INTERNAL_STATE_VCONF_KEY);
549 throw runtime::Exception("Failed to get vconf value");
552 std::string valueStr(value);
555 if (valueStr == "encrypted") {
556 return State::Encrypted;
557 } else if (valueStr == "unencrypted") {
558 return State::Unencrypted;
560 return State::Corrupted;
566 unsigned int InternalEncryption::getSupportedOptions()
568 return engine->getSupportedOptions();