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
23 #include <sys/mount.h>
24 #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>
35 #include <klay/error.h>
39 #include "progress-bar.h"
41 #include "internal-encryption.h"
47 const char *INTERNAL_DEV_PATH = "/dev/disk/by-partlabel";
48 const char *INTERNAL_DEV_NAME = "USER";
49 const char *INTERNAL_PATH = "/opt/usr";
51 const char *PRIVILEGE_PLATFORM = "http://tizen.org/privilege/internal/default/platform";
53 // TODO: see recovery()
54 const std::string PROG_FACTORY_RESET = "/usr/bin/dbus-send";
55 const std::vector<std::string> wipeCommand = {
60 "--dest=com.samsung.factoryreset",
61 "/com/samsung/factoryreset",
62 "com.samsung.factoryreset.start.setting"
65 std::string findDevPath()
67 std::string source = INTERNAL_DEV_PATH + std::string("/") + INTERNAL_DEV_NAME;
69 runtime::DirectoryIterator iter(INTERNAL_DEV_PATH), end;
72 const std::string& path = (*iter).getPath();
73 std::string name = path.substr(path.rfind('/') + 1);
75 upper.reserve(name.size());
77 upper += std::toupper(c);
79 if (upper.compare(0, strlen(INTERNAL_DEV_NAME), INTERNAL_DEV_NAME) == 0) {
85 } catch (runtime::Exception &e) {}
87 char *dev = ::realpath(source.c_str(), NULL);
89 ERROR(SINK, "Failed to get device path.");
93 std::string devPath(dev);
99 void stopKnownSystemdServices()
101 std::vector<std::string> knownSystemdServices;
102 dbus::Connection& systemDBus = dbus::Connection::getSystem();
103 dbus::VariantIterator iter;
105 systemDBus.methodcall("org.freedesktop.systemd1",
106 "/org/freedesktop/systemd1",
107 "org.freedesktop.systemd1.Manager",
109 -1, "(a(ssssssouso))", "")
110 .get("(a(ssssssouso))", &iter);
113 unsigned int dataUint;
117 ret = iter.get("(ssssssouso)", dataStr, dataStr + 1, dataStr + 2,
118 dataStr + 3, dataStr + 4, dataStr + 5,
119 dataStr + 6, &dataUint, dataStr + 7,
126 std::string service(dataStr[0]);
127 if (service.compare(0, 5, "user@") == 0 ||
128 service == "tlm.service" ||
129 service == "resourced.service") {
130 knownSystemdServices.push_back(service);
134 for (const std::string& service : knownSystemdServices) {
135 INFO(SINK, "Stopping service: " + service);
136 systemDBus.methodcall("org.freedesktop.systemd1",
137 "/org/freedesktop/systemd1",
138 "org.freedesktop.systemd1.Manager",
140 -1, "", "(ss)", service.c_str(), "flush");
146 void stopDependedSystemdServices()
148 dbus::Connection& systemDBus = dbus::Connection::getSystem();
149 std::set<std::string> servicesToStop;
151 for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
154 systemDBus.methodcall("org.freedesktop.systemd1",
155 "/org/freedesktop/systemd1",
156 "org.freedesktop.systemd1.Manager",
158 -1, "(o)", "(u)", (unsigned int)pid)
159 .get("(o)", &service);
160 servicesToStop.insert(service);
161 } catch (runtime::Exception &e) {
162 INFO(SINK, "Killing process: " + std::to_string(pid));
163 ::kill(pid, SIGKILL);
167 for (const std::string& service : servicesToStop) {
168 INFO(SINK, "Stopping service: " + service);
169 systemDBus.methodcall("org.freedesktop.systemd1",
171 "org.freedesktop.systemd1.Unit",
173 -1, "", "(s)", "flush");
177 void showProgressUI(const std::string type)
179 ::tzplatform_set_user(::tzplatform_getuid(TZ_SYS_DEFAULT_USER));
180 std::string defaultUserHome(::tzplatform_getenv(TZ_USER_HOME));
181 ::tzplatform_reset_user();
184 runtime::File shareDirectory("/opt/home/root/share");
185 if (!shareDirectory.exists()) {
186 shareDirectory.makeDirectory(true);
189 runtime::File elmConfigDir(shareDirectory.getPath() + "/.elementary");
190 if (!elmConfigDir.exists()) {
191 runtime::File defaultElmConfigDir(defaultUserHome + "/share/.elementary");
192 defaultElmConfigDir.copyTo(shareDirectory.getPath());
194 } catch (runtime::Exception &e) {
195 ERROR(SINK, "Failed to set up elm configuration: " + std::string(e.what()));
198 std::vector<std::string> args = {
199 "ode", "progress", type, "Internal"
202 runtime::Process proc("/usr/bin/ode", args);
206 unsigned int getOptions()
208 unsigned int result = 0;
212 ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
214 result |= InternalEncryption::Option::IncludeUnusedRegion;
220 void setOptions(unsigned int options)
224 if (options & InternalEncryption::Option::IncludeUnusedRegion) {
229 ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
234 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv) :
237 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
238 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)());
239 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
240 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
241 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
242 server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
243 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
244 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
245 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
246 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
247 server.expose(this, "", (int)(InternalEncryptionServer::getState)());
248 server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
250 server.createNotification("InternalEncryptionServer::mount");
252 std::string source = findDevPath();
254 engine.reset(new INTERNAL_ENGINE(
255 source, INTERNAL_PATH,
256 ProgressBar([](int v) {
257 ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
258 std::to_string(v).c_str());
263 InternalEncryptionServer::~InternalEncryptionServer()
267 int InternalEncryptionServer::setMountPassword(const std::string& password)
269 KeyManager::data pwData(password.begin(), password.end());
270 KeyManager keyManager(engine->getKeyMeta());
271 if (!keyManager.verifyPassword(pwData)) {
272 ERROR(SINK, "Wrong password passed.");
276 mountKey = keyManager.getMasterKey(pwData);
281 int InternalEncryptionServer::mount()
283 if (mountKey.empty()) {
284 ERROR(SINK, "You need to call set_mount_password() first.");
288 KeyManager::data key = mountKey;
291 if (getState() != State::Encrypted) {
292 INFO(SINK, "Cannot mount, SD partition's state incorrect.");
296 if (engine->isMounted()) {
297 INFO(SINK, "Partition already mounted.");
301 INFO(SINK, "Mounting internal storage.");
303 engine->mount(key, getOptions());
305 server.notify("InternalEncryptionServer::mount");
307 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
308 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
309 } catch (runtime::Exception &e) {
310 ERROR(SINK, "Mount failed: " + std::string(e.what()));
317 int InternalEncryptionServer::umount()
319 if (getState() != State::Encrypted) {
320 ERROR(SINK, "Cannot umount, partition's state incorrect.");
324 if (!engine->isMounted()) {
325 INFO(SINK, "Partition already umounted.");
329 INFO(SINK, "Closing all processes using internal storage.");
331 stopDependedSystemdServices();
332 INFO(SINK, "Umounting internal storage.");
334 } catch (runtime::Exception &e) {
335 ERROR(SINK, "Umount failed: " + std::string(e.what()));
342 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
344 if (getState() != State::Unencrypted) {
345 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
349 KeyManager::data pwData(password.begin(), password.end());
350 KeyManager keyManager(engine->getKeyMeta());
352 if (!keyManager.verifyPassword(pwData)) {
353 ERROR(SINK, "Wrong password passed.");
357 KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
358 auto encryptWorker = [MasterKey, options, this]() {
360 std::string source = engine->getSource();
361 std::string mntPath = findMountPointByDevice(source);
363 if (!mntPath.empty()) {
364 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
365 stopKnownSystemdServices();
366 INFO(SINK, "Closing all processes using internal storage.");
367 stopDependedSystemdServices();
370 while (!mntPath.empty()) {
371 INFO(SINK, "Umounting internal storage.");
372 while (::umount(mntPath.c_str()) == -1) {
373 if (errno != EBUSY) {
374 throw runtime::Exception("Umount error: " + runtime::GetSystemErrorMessage());
376 stopDependedSystemdServices();
378 mntPath = findMountPointByDevice(source);
381 showProgressUI("Encrypting");
383 INFO(SINK, "Encryption started.");
384 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
385 engine->encrypt(MasterKey, options);
386 setOptions(options & getSupportedOptions());
388 INFO(SINK, "Encryption completed.");
389 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
390 server.notify("InternalEncryptionServer::mount");
392 INFO(SINK, "Syncing disk and rebooting.");
394 ::reboot(RB_AUTOBOOT);
395 } catch (runtime::Exception &e) {
396 ERROR(SINK, "Encryption failed: " + std::string(e.what()));
400 std::thread asyncWork(encryptWorker);
406 int InternalEncryptionServer::decrypt(const std::string& password)
408 if (getState() != State::Encrypted) {
409 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
413 KeyManager::data pwData(password.begin(), password.end());
414 KeyManager keyManager(engine->getKeyMeta());
416 if (!keyManager.verifyPassword(pwData)) {
417 ERROR(SINK, "Wrong password passed.");
421 KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
422 auto decryptWorker = [MasterKey, this]() {
424 if (engine->isMounted()) {
425 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
426 stopKnownSystemdServices();
427 INFO(SINK, "Closing all processes using internal storage.");
428 stopDependedSystemdServices();
430 INFO(SINK, "Umounting internal storage.");
435 } catch (runtime::Exception& e) {
436 stopDependedSystemdServices();
441 showProgressUI("Decrypting");
443 INFO(SINK, "Decryption started.");
444 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
445 engine->decrypt(MasterKey, getOptions());
447 INFO(SINK, "Decryption complete.");
448 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
450 INFO(SINK, "Syncing disk and rebooting.");
452 ::reboot(RB_AUTOBOOT);
453 } catch (runtime::Exception &e) {
454 ERROR(SINK, "Decryption failed: " + std::string(e.what()));
458 std::thread asyncWork(decryptWorker);
464 int InternalEncryptionServer::recovery()
466 if (getState() != State::Unencrypted) {
471 runtime::Process proc(PROG_FACTORY_RESET, wipeCommand);
472 if (proc.execute() == -1) {
473 ERROR(SINK, "Failed to launch factory-reset");
480 int InternalEncryptionServer::isPasswordInitialized()
482 if (engine->isKeyMetaSet()) {
488 int InternalEncryptionServer::initPassword(const std::string& password)
490 KeyManager::data pwData(password.begin(), password.end());
491 KeyManager keyManager;
493 keyManager.initPassword(pwData);
494 engine->setKeyMeta(keyManager.serialize());
498 int InternalEncryptionServer::cleanPassword(const std::string& password)
500 KeyManager::data pwData(password.begin(), password.end());
501 KeyManager keyManager(engine->getKeyMeta());
503 if (!keyManager.verifyPassword(pwData)) {
504 ERROR(SINK, "Wrong password passed.");
508 engine->clearKeyMeta();
512 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
513 const std::string& newPassword)
515 KeyManager::data oldPwData(oldPassword.begin(), oldPassword.end());
516 KeyManager::data newPwData(newPassword.begin(), newPassword.end());
517 KeyManager keyManager(engine->getKeyMeta());
519 if (!keyManager.verifyPassword(oldPwData)) {
520 ERROR(SINK, "Wrong password passed.");
524 keyManager.changePassword(oldPwData, newPwData);
525 engine->setKeyMeta(keyManager.serialize());
530 int InternalEncryptionServer::verifyPassword(const std::string& password)
532 KeyManager::data pwData(password.begin(), password.end());
533 KeyManager keyManager(engine->getKeyMeta());
535 if (keyManager.verifyPassword(pwData)) {
541 int InternalEncryptionServer::getState()
543 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
545 throw runtime::Exception("Failed to get vconf value.");
548 std::string valueStr(value);
551 if (valueStr == "encrypted") {
552 return State::Encrypted;
553 } else if (valueStr == "unencrypted") {
554 return State::Unencrypted;
556 return State::Corrupted;
562 unsigned int InternalEncryptionServer::getSupportedOptions()
564 return engine->getSupportedOptions();