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"
40 #include "rmi/common.h"
42 #include "internal-encryption.h"
48 const char *INTERNAL_DEV_PATH = "/dev/disk/by-partlabel";
49 const char *INTERNAL_DEV_NAME = "USER";
50 const char *INTERNAL_PATH = "/opt/usr";
52 const char *PRIVILEGE_PLATFORM = "http://tizen.org/privilege/internal/default/platform";
54 // TODO: see recovery()
55 const std::string PROG_FACTORY_RESET = "/usr/bin/dbus-send";
56 const std::vector<std::string> wipeCommand = {
61 "--dest=com.samsung.factoryreset",
62 "/com/samsung/factoryreset",
63 "com.samsung.factoryreset.start.setting"
66 std::string findDevPath()
68 std::string source = INTERNAL_DEV_PATH + std::string("/") + INTERNAL_DEV_NAME;
70 runtime::DirectoryIterator iter(INTERNAL_DEV_PATH), end;
73 const std::string& path = (*iter).getPath();
74 std::string name = path.substr(path.rfind('/') + 1);
76 upper.reserve(name.size());
78 upper += std::toupper(c);
80 if (upper.compare(0, strlen(INTERNAL_DEV_NAME), INTERNAL_DEV_NAME) == 0) {
86 } catch (runtime::Exception &e) {}
88 char *dev = ::realpath(source.c_str(), NULL);
90 ERROR(SINK, "Failed to get device path.");
94 std::string devPath(dev);
100 void stopKnownSystemdServices()
102 std::vector<std::string> knownSystemdServices;
103 dbus::Connection& systemDBus = dbus::Connection::getSystem();
104 dbus::VariantIterator iter;
106 systemDBus.methodcall("org.freedesktop.systemd1",
107 "/org/freedesktop/systemd1",
108 "org.freedesktop.systemd1.Manager",
110 -1, "(a(ssssssouso))", "")
111 .get("(a(ssssssouso))", &iter);
114 unsigned int dataUint;
118 ret = iter.get("(ssssssouso)", dataStr, dataStr + 1, dataStr + 2,
119 dataStr + 3, dataStr + 4, dataStr + 5,
120 dataStr + 6, &dataUint, dataStr + 7,
127 std::string service(dataStr[0]);
128 if (service.compare(0, 5, "user@") == 0 ||
129 service == "tlm.service" ||
130 service == "resourced.service") {
131 knownSystemdServices.push_back(service);
135 for (const std::string& service : knownSystemdServices) {
136 INFO(SINK, "Stopping service: " + service);
137 systemDBus.methodcall("org.freedesktop.systemd1",
138 "/org/freedesktop/systemd1",
139 "org.freedesktop.systemd1.Manager",
141 -1, "", "(ss)", service.c_str(), "flush");
147 void stopDependedSystemdServices()
149 dbus::Connection& systemDBus = dbus::Connection::getSystem();
150 std::set<std::string> servicesToStop;
152 for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
155 systemDBus.methodcall("org.freedesktop.systemd1",
156 "/org/freedesktop/systemd1",
157 "org.freedesktop.systemd1.Manager",
159 -1, "(o)", "(u)", (unsigned int)pid)
160 .get("(o)", &service);
161 servicesToStop.insert(service);
162 } catch (runtime::Exception &e) {
163 INFO(SINK, "Killing process: " + std::to_string(pid));
164 ::kill(pid, SIGKILL);
168 for (const std::string& service : servicesToStop) {
169 INFO(SINK, "Stopping service: " + service);
170 systemDBus.methodcall("org.freedesktop.systemd1",
172 "org.freedesktop.systemd1.Unit",
174 -1, "", "(s)", "flush");
178 void showProgressUI(const std::string type)
180 ::tzplatform_set_user(::tzplatform_getuid(TZ_SYS_DEFAULT_USER));
181 std::string defaultUserHome(::tzplatform_getenv(TZ_USER_HOME));
182 ::tzplatform_reset_user();
185 runtime::File shareDirectory("/opt/home/root/share");
186 if (!shareDirectory.exists()) {
187 shareDirectory.makeDirectory(true);
190 runtime::File elmConfigDir(shareDirectory.getPath() + "/.elementary");
191 if (!elmConfigDir.exists()) {
192 runtime::File defaultElmConfigDir(defaultUserHome + "/share/.elementary");
193 defaultElmConfigDir.copyTo(shareDirectory.getPath());
195 } catch (runtime::Exception &e) {
196 ERROR(SINK, "Failed to set up elm configuration: " + std::string(e.what()));
199 std::vector<std::string> args = {
200 "ode", "progress", type, "Internal"
203 runtime::Process proc("/usr/bin/ode", args);
207 unsigned int getOptions()
209 unsigned int result = 0;
213 ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
215 result |= InternalEncryption::Option::IncludeUnusedRegion;
221 void setOptions(unsigned int options)
225 if (options & InternalEncryption::Option::IncludeUnusedRegion) {
230 ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
235 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv,
240 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
241 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)());
242 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
243 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
244 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
245 server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
246 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
247 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
248 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
249 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
250 server.expose(this, "", (int)(InternalEncryptionServer::getState)());
251 server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
252 server.expose(this, "", (std::string)(InternalEncryptionServer::getDevicePath)());
254 server.createNotification("InternalEncryptionServer::mount");
256 std::string source = findDevPath();
258 engine.reset(new INTERNAL_ENGINE(
259 source, INTERNAL_PATH,
260 ProgressBar([](int v) {
261 ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
262 std::to_string(v).c_str());
267 InternalEncryptionServer::~InternalEncryptionServer()
271 int InternalEncryptionServer::setMountPassword(const std::string& password)
273 return keyServer.get(engine->getSource(), password, mountKey);
276 int InternalEncryptionServer::mount()
278 if (mountKey.empty()) {
279 ERROR(SINK, "You need to call set_mount_password() first.");
280 return error::NoData;
283 BinaryData key = mountKey;
286 if (getState() != State::Encrypted) {
287 INFO(SINK, "Cannot mount, SD partition's state incorrect.");
288 return error::NoSuchDevice;
291 if (engine->isMounted()) {
292 INFO(SINK, "Partition already mounted.");
296 INFO(SINK, "Mounting 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()));
306 return error::Unknown;
312 int InternalEncryptionServer::umount()
314 if (getState() != State::Encrypted) {
315 ERROR(SINK, "Cannot umount, partition's state incorrect.");
316 return error::NoSuchDevice;
319 if (!engine->isMounted()) {
320 INFO(SINK, "Partition already umounted.");
324 INFO(SINK, "Closing all processes using internal storage.");
326 stopDependedSystemdServices();
327 INFO(SINK, "Umounting internal storage.");
329 } catch (runtime::Exception &e) {
330 ERROR(SINK, "Umount failed: " + std::string(e.what()));
331 return error::Unknown;
337 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
339 if (getState() != State::Unencrypted) {
340 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
341 return error::NoSuchDevice;
344 BinaryData masterKey;
345 int ret = keyServer.get(engine->getSource(), password, masterKey);
346 if (ret != error::None)
349 auto encryptWorker = [masterKey, options, this]() {
351 std::string source = engine->getSource();
352 std::string mntPath = findMountPointByDevice(source);
354 if (!mntPath.empty()) {
355 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
356 stopKnownSystemdServices();
357 INFO(SINK, "Closing all processes using internal storage.");
358 stopDependedSystemdServices();
361 while (!mntPath.empty()) {
362 INFO(SINK, "Umounting internal storage.");
363 while (::umount(mntPath.c_str()) == -1) {
364 if (errno != EBUSY) {
365 throw runtime::Exception("Umount error: " + runtime::GetSystemErrorMessage());
367 stopDependedSystemdServices();
369 mntPath = findMountPointByDevice(source);
372 showProgressUI("Encrypting");
374 INFO(SINK, "Encryption started.");
375 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
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 ERROR(SINK, "Encryption failed: " + std::string(e.what()));
391 std::thread asyncWork(encryptWorker);
397 int InternalEncryptionServer::decrypt(const std::string& password)
399 if (getState() != State::Encrypted) {
400 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
401 return error::NoSuchDevice;
404 BinaryData masterKey;
405 int ret = keyServer.get(engine->getSource(), password, masterKey);
406 if (ret != error::None)
409 auto decryptWorker = [masterKey, this]() {
411 if (engine->isMounted()) {
412 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
413 stopKnownSystemdServices();
414 INFO(SINK, "Closing all processes using internal storage.");
415 stopDependedSystemdServices();
417 INFO(SINK, "Umounting internal storage.");
422 } catch (runtime::Exception& e) {
423 stopDependedSystemdServices();
428 showProgressUI("Decrypting");
430 INFO(SINK, "Decryption started.");
431 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
432 engine->decrypt(masterKey, getOptions());
434 INFO(SINK, "Decryption complete.");
435 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
437 INFO(SINK, "Syncing disk and rebooting.");
439 ::reboot(RB_AUTOBOOT);
440 } catch (runtime::Exception &e) {
441 ERROR(SINK, "Decryption failed: " + std::string(e.what()));
445 std::thread asyncWork(decryptWorker);
451 int InternalEncryptionServer::recovery()
453 if (getState() == State::Unencrypted) {
454 return error::NoSuchDevice;
458 runtime::Process proc(PROG_FACTORY_RESET, wipeCommand);
459 if (proc.execute() == -1) {
460 ERROR(SINK, "Failed to launch factory-reset");
461 return error::WrongPassword;
467 int InternalEncryptionServer::isPasswordInitialized()
469 return keyServer.isInitialized(engine->getSource());
472 int InternalEncryptionServer::initPassword(const std::string& password)
474 return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
477 int InternalEncryptionServer::cleanPassword(const std::string& password)
479 return keyServer.remove(engine->getSource(), password);
482 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
483 const std::string& newPassword)
485 return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
488 int InternalEncryptionServer::verifyPassword(const std::string& password)
490 return keyServer.verifyPassword(engine->getSource(), password);
493 int InternalEncryptionServer::getState()
495 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
497 throw runtime::Exception("Failed to get vconf value.");
500 std::string valueStr(value);
503 if (valueStr == "encrypted") {
504 return State::Encrypted;
505 } else if (valueStr == "unencrypted") {
506 return State::Unencrypted;
508 return State::Corrupted;
512 unsigned int InternalEncryptionServer::getSupportedOptions()
514 return engine->getSupportedOptions();
517 std::string InternalEncryptionServer::getDevicePath() const
519 return engine->getSource();