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>
38 #include "progress-bar.h"
40 #include "internal-encryption.h"
46 const char *INTERNAL_DEV_PATH = "/dev/disk/by-partlabel";
47 const char *INTERNAL_DEV_NAME = "USER";
48 const char *INTERNAL_PATH = "/opt/usr";
50 const char *PRIVILEGE_PLATFORM = "http://tizen.org/privilege/internal/default/platform";
52 // TODO: see recovery()
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"
64 std::string findDevPath()
66 std::string source = INTERNAL_DEV_PATH + std::string("/") + INTERNAL_DEV_NAME;
68 runtime::DirectoryIterator iter(INTERNAL_DEV_PATH), end;
71 const std::string& path = (*iter).getPath();
72 std::string name = path.substr(path.rfind('/') + 1);
74 upper.reserve(name.size());
76 upper += std::toupper(c);
78 if (upper.compare(0, strlen(INTERNAL_DEV_NAME), INTERNAL_DEV_NAME) == 0) {
84 } catch (runtime::Exception &e) {}
86 char *dev = ::realpath(source.c_str(), NULL);
88 ERROR(SINK, "failed to get device path");
92 std::string devPath(dev);
98 void stopKnownSystemdServices() {
99 std::vector<std::string> knownSystemdServices;
100 dbus::Connection& systemDBus = dbus::Connection::getSystem();
101 dbus::VariantIterator iter;
103 systemDBus.methodcall("org.freedesktop.systemd1",
104 "/org/freedesktop/systemd1",
105 "org.freedesktop.systemd1.Manager",
107 -1, "(a(ssssssouso))", "")
108 .get("(a(ssssssouso))", &iter);
111 unsigned int dataUint;
115 ret = iter.get("(ssssssouso)", dataStr, dataStr + 1, dataStr + 2,
116 dataStr + 3, dataStr + 4, dataStr + 5,
117 dataStr + 6, &dataUint, dataStr + 7,
124 std::string service(dataStr[0]);
125 if (service.compare(0, 5, "user@") == 0 ||
126 service == "tlm.service" ||
127 service == "resourced.service") {
128 knownSystemdServices.push_back(service);
132 for (const std::string& service : knownSystemdServices) {
133 INFO(SINK, "Stop service - " + service);
134 systemDBus.methodcall("org.freedesktop.systemd1",
135 "/org/freedesktop/systemd1",
136 "org.freedesktop.systemd1.Manager",
138 -1, "", "(ss)", service.c_str(), "flush");
144 void stopDependedSystemdServices()
146 dbus::Connection& systemDBus = dbus::Connection::getSystem();
147 std::set<std::string> servicesToStop;
149 for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
152 systemDBus.methodcall("org.freedesktop.systemd1",
153 "/org/freedesktop/systemd1",
154 "org.freedesktop.systemd1.Manager",
156 -1, "(o)", "(u)", (unsigned int)pid)
157 .get("(o)", &service);
158 servicesToStop.insert(service);
159 } catch (runtime::Exception &e) {
160 INFO(SINK, "Close process - " + std::to_string(pid));
161 ::kill(pid, SIGKILL);
165 for (const std::string& service : servicesToStop) {
166 INFO(SINK, "Close service - " + service);
167 systemDBus.methodcall("org.freedesktop.systemd1",
169 "org.freedesktop.systemd1.Unit",
171 -1, "", "(s)", "flush");
175 void showProgressUI(const std::string type) {
176 ::tzplatform_set_user(::tzplatform_getuid(TZ_SYS_DEFAULT_USER));
177 std::string defaultUserHome(::tzplatform_getenv(TZ_USER_HOME));
178 ::tzplatform_reset_user();
181 runtime::File shareDirectory("/opt/home/root/share");
182 if (!shareDirectory.exists()) {
183 shareDirectory.makeDirectory(true);
186 runtime::File elmConfigDir(shareDirectory.getPath() + "/.elementary");
187 if (!elmConfigDir.exists()) {
188 runtime::File defaultElmConfigDir(defaultUserHome + "/share/.elementary");
189 defaultElmConfigDir.copyTo(shareDirectory.getPath());
191 } catch (runtime::Exception &e) {
192 ERROR(SINK, "Failed to set up elm configuration");
195 std::vector<std::string> args = {
196 "ode", "progress", type, "Internal"
199 runtime::Process proc("/usr/bin/ode", args);
203 unsigned int getOptions()
205 unsigned int result = 0;
209 ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
211 result |= InternalEncryption::Option::IncludeUnusedRegion;
217 void setOptions(unsigned int options)
221 if (options & InternalEncryption::Option::IncludeUnusedRegion) {
226 ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
231 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv) :
234 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
235 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)());
236 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
237 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
238 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
239 server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
240 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
241 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
242 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
243 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
244 server.expose(this, "", (int)(InternalEncryptionServer::getState)());
245 server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
247 server.createNotification("InternalEncryptionServer::mount");
249 std::string source = findDevPath();
251 engine.reset(new INTERNAL_ENGINE(
252 source, INTERNAL_PATH,
253 ProgressBar([](int v) {
254 ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
255 std::to_string(v).c_str());
260 InternalEncryptionServer::~InternalEncryptionServer()
264 int InternalEncryptionServer::setMountPassword(const std::string& password)
266 KeyManager::data pwData(password.begin(), password.end());
267 KeyManager keyManager(engine->getKeyMeta());
268 if (!keyManager.verifyPassword(pwData)) {
272 mountKey = keyManager.getMasterKey(pwData);
277 int InternalEncryptionServer::mount()
279 if (mountKey.empty()) {
280 ERROR(SINK, "You need to call set_mount_password() first");
284 KeyManager::data key = mountKey;
287 if (getState() != State::Encrypted) {
291 if (engine->isMounted()) {
292 INFO(SINK, "Already mounted");
297 INFO(SINK, "Mount internal storage...");
298 engine->mount(key, getOptions());
300 server.notify("InternalEncryptionServer::mount");
302 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
303 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
304 } catch (runtime::Exception &e) {
305 ERROR(SINK, "Mount failed - " + std::string(e.what()));
312 int InternalEncryptionServer::umount()
314 if (getState() != State::Encrypted) {
318 if (!engine->isMounted()) {
319 INFO(SINK, "Already umounted");
324 INFO(SINK, "Close all processes using internal storage...");
325 stopDependedSystemdServices();
326 INFO(SINK, "Umount internal storage...");
328 } catch (runtime::Exception &e) {
329 ERROR(SINK, "Umount failed - " + std::string(e.what()));
336 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
338 if (getState() != State::Unencrypted) {
342 KeyManager::data pwData(password.begin(), password.end());
343 KeyManager keyManager(engine->getKeyMeta());
345 if (!keyManager.verifyPassword(pwData)) {
349 KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
350 auto encryptWorker = [MasterKey, options, this]() {
352 std::string source = engine->getSource();
353 std::string mntPath = findMntPath(source);
355 if (!mntPath.empty()) {
356 INFO(SINK, "Close all known systemd services that might be using internal storage...");
357 stopKnownSystemdServices();
358 INFO(SINK, "Close all processes using internal storage...");
359 stopDependedSystemdServices();
362 while (!mntPath.empty()) {
363 INFO(SINK, "Umount internal storage...");
364 while (::umount(mntPath.c_str()) == -1) {
365 if (errno != EBUSY) {
366 throw runtime::Exception("Umount error - " + std::to_string(errno));
368 stopDependedSystemdServices();
370 mntPath = findMntPath(source);
373 showProgressUI("Encrypting");
375 INFO(SINK, "Encryption started...");
376 engine->encrypt(MasterKey, options);
377 setOptions(options & getSupportedOptions());
379 INFO(SINK, "Encryption completed");
380 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
381 server.notify("InternalEncryptionServer::mount");
383 INFO(SINK, "Syncing disk and rebooting...");
385 ::reboot(RB_AUTOBOOT);
386 } catch (runtime::Exception &e) {
387 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
388 ERROR(SINK, "Encryption failed - " + std::string(e.what()));
392 std::thread asyncWork(encryptWorker);
398 int InternalEncryptionServer::decrypt(const std::string& password)
400 if (getState() != State::Encrypted) {
404 KeyManager::data pwData(password.begin(), password.end());
405 KeyManager keyManager(engine->getKeyMeta());
407 if (!keyManager.verifyPassword(pwData)) {
411 KeyManager::data MasterKey = keyManager.getMasterKey(pwData);
412 auto decryptWorker = [MasterKey, this]() {
414 if (engine->isMounted()) {
415 INFO(SINK, "Close all known systemd services that might be using internal storage...");
416 stopKnownSystemdServices();
417 INFO(SINK, "Close all processes using internal storage...");
418 stopDependedSystemdServices();
420 INFO(SINK, "Umount internal storage...");
425 } catch (runtime::Exception& e) {
426 stopDependedSystemdServices();
431 showProgressUI("Decrypting");
433 INFO(SINK, "Decryption started...");
434 engine->decrypt(MasterKey, getOptions());
436 INFO(SINK, "Decryption completed");
437 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
439 INFO(SINK, "Syncing disk and rebooting...");
441 ::reboot(RB_AUTOBOOT);
442 } catch (runtime::Exception &e) {
443 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
444 ERROR(SINK, "Decryption failed - " + std::string(e.what()));
448 std::thread asyncWork(decryptWorker);
454 int InternalEncryptionServer::recovery()
456 if (getState() != State::Unencrypted) {
461 runtime::Process proc(PROG_FACTORY_RESET, wipeCommand);
462 if (proc.execute() == -1) {
463 ERROR(SINK, "Failed to launch factory-reset");
470 int InternalEncryptionServer::isPasswordInitialized()
472 if (engine->isKeyMetaSet()) {
478 int InternalEncryptionServer::initPassword(const std::string& password)
480 KeyManager::data pwData(password.begin(), password.end());
481 KeyManager keyManager;
483 keyManager.initPassword(pwData);
484 engine->setKeyMeta(keyManager.serialize());
488 int InternalEncryptionServer::cleanPassword(const std::string& password)
490 KeyManager::data pwData(password.begin(), password.end());
491 KeyManager keyManager(engine->getKeyMeta());
493 if (!keyManager.verifyPassword(pwData)) {
497 engine->clearKeyMeta();
501 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
502 const std::string& newPassword)
504 KeyManager::data oldPwData(oldPassword.begin(), oldPassword.end());
505 KeyManager::data newPwData(newPassword.begin(), newPassword.end());
506 KeyManager keyManager(engine->getKeyMeta());
508 if (!keyManager.verifyPassword(oldPwData)) {
512 keyManager.changePassword(oldPwData, newPwData);
513 engine->setKeyMeta(keyManager.serialize());
518 int InternalEncryptionServer::verifyPassword(const std::string& password)
520 KeyManager::data pwData(password.begin(), password.end());
521 KeyManager keyManager(engine->getKeyMeta());
523 if (keyManager.verifyPassword(pwData)) {
529 int InternalEncryptionServer::getState()
531 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
533 throw runtime::Exception("Failed to get vconf value");
536 std::string valueStr(value);
539 if (valueStr == "encrypted") {
540 return State::Encrypted;
541 } else if (valueStr == "unencrypted") {
542 return State::Unencrypted;
544 return State::Corrupted;
550 unsigned int InternalEncryptionServer::getSupportedOptions()
552 return engine->getSupportedOptions();