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";
55 const mode_t MODE_0640 = S_IRUSR | S_IWUSR | S_IRGRP;
57 // watches systemd jobs
60 explicit JobWatch(dbus::Connection& systemDBus);
63 bool waitForJob(const std::string& job);
66 void jobRemoved(const dbus::Variant& parameters);
70 const std::string& job,
71 const std::string& unit,
72 const std::string& result) : id(id), job(job), unit(unit), result(result) {}
79 dbus::Connection::SubscriptionId id;
80 dbus::Connection& systemDBus;
81 std::list<Job> removedJobs;
83 std::condition_variable jobsCv;
86 JobWatch::JobWatch(dbus::Connection& systemDBus) : systemDBus(systemDBus) {
87 auto callback = [this](dbus::Variant parameters) {
88 this->jobRemoved(parameters);
91 id = systemDBus.subscribeSignal("",
92 "/org/freedesktop/systemd1",
93 "org.freedesktop.systemd1.Manager",
98 JobWatch::~JobWatch() {
99 systemDBus.unsubscribeSignal(id);
102 bool JobWatch::waitForJob(const std::string& job) {
104 std::unique_lock<std::mutex> lock(jobsMutex);
105 jobsCv.wait(lock, [this]{ return !removedJobs.empty(); });
107 while(!removedJobs.empty()) {
108 bool match = (removedJobs.front().job == job);
109 bool done = (removedJobs.front().result == "done");
110 removedJobs.pop_front();
117 void JobWatch::jobRemoved(const dbus::Variant& parameters)
123 parameters.get("(uoss)", &id, &job, &unit, &result);
124 INFO(SINK, "id:" + std::to_string(id) + " job:" + job + " unit:" + unit + " result:" + result);
127 std::lock_guard<std::mutex> guard(jobsMutex);
128 removedJobs.emplace_back(id, job, unit, result);
133 void stopKnownSystemdUnits()
135 std::vector<std::string> knownSystemdUnits;
136 dbus::Connection& systemDBus = dbus::Connection::getSystem();
137 dbus::VariantIterator iter;
139 systemDBus.methodcall("org.freedesktop.systemd1",
140 "/org/freedesktop/systemd1",
141 "org.freedesktop.systemd1.Manager",
143 -1, "(a(ssssssouso))", "")
144 .get("(a(ssssssouso))", &iter);
147 unsigned int dataUint;
151 ret = iter.get("(ssssssouso)", dataStr, dataStr + 1, dataStr + 2,
152 dataStr + 3, dataStr + 4, dataStr + 5,
153 dataStr + 6, &dataUint, dataStr + 7,
160 std::string unit(dataStr[0]);
161 if (unit == "security-manager.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 knownSystemdUnits.push_back(unit);
171 JobWatch watch(systemDBus);
173 for (const std::string& unit : knownSystemdUnits) {
174 INFO(SINK, "Stopping unit: " + unit);
175 const char* job = NULL;
176 systemDBus.methodcall("org.freedesktop.systemd1",
177 "/org/freedesktop/systemd1",
178 "org.freedesktop.systemd1.Manager",
180 -1, "(o)", "(ss)", unit.c_str(), "flush").get("(o)", &job);
181 INFO(SINK, "Waiting for job: " + std::string(job));
182 if (!watch.waitForJob(job))
183 throw runtime::Exception("Stopping unit: " + unit + " failed");
187 void stopDependedSystemdUnits()
189 dbus::Connection& systemDBus = dbus::Connection::getSystem();
190 std::set<std::string> unitsToStop;
192 for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
195 systemDBus.methodcall("org.freedesktop.systemd1",
196 "/org/freedesktop/systemd1",
197 "org.freedesktop.systemd1.Manager",
199 -1, "(o)", "(u)", (unsigned int)pid)
201 unitsToStop.insert(unit);
202 } catch (runtime::Exception &e) {
203 INFO(SINK, "Killing process: " + std::to_string(pid));
204 ::kill(pid, SIGKILL);
208 JobWatch watch(systemDBus);
210 for (const std::string& unit : unitsToStop) {
211 INFO(SINK, "Stopping unit: " + unit);
212 const char* job = NULL;
213 systemDBus.methodcall("org.freedesktop.systemd1",
215 "org.freedesktop.systemd1.Unit",
217 -1, "(o)", "(s)", "flush").get("(o)", &job);
218 INFO(SINK, "Waiting for job: " + std::string(job));
219 if (!watch.waitForJob(job))
220 throw runtime::Exception("Stopping unit: " + unit + " failed");
224 void showProgressUI(const std::string type)
226 dbus::Connection& systemDBus = dbus::Connection::getSystem();
227 std::string unit("ode-progress-ui@"+type+".service");
229 JobWatch watch(systemDBus);
230 INFO(SINK, "Start unit: " + unit);
232 const char* job = NULL;
233 systemDBus.methodcall("org.freedesktop.systemd1",
234 "/org/freedesktop/systemd1",
235 "org.freedesktop.systemd1.Manager",
237 -1, "(o)", "(ss)", unit.c_str(), "replace").get("(o)", &job);
239 INFO(SINK, "Waiting for job: " + std::string(job));
240 if (!watch.waitForJob(job))
241 throw runtime::Exception("Starting unit: " + unit + " failed");
244 unsigned int getOptions()
246 unsigned int result = 0;
250 ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
252 result |= InternalEncryption::Option::IncludeUnusedRegion;
258 void setOptions(unsigned int options)
262 if (options & InternalEncryption::Option::IncludeUnusedRegion) {
267 ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
270 void unmountInternalStorage(const std::string& source)
273 auto mntPaths = findMountPointsByDevice(source);
277 bool unmounted = true;
278 for(const auto& path : mntPaths) {
279 INFO(SINK, "Unmounting " + path);
280 if (::umount(path.c_str()) == -1) {
281 // If it's busy or was already unmounted ignore the error
282 if (errno != EBUSY && errno != EINVAL) {
283 throw runtime::Exception("umount() error: " + runtime::GetSystemErrorMessage());
289 stopDependedSystemdUnits();
295 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv, KeyServer& key) :
299 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
300 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)());
301 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
302 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
303 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
304 server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
305 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::recovery)());
306 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
307 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
308 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
309 server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
310 server.expose(this, "", (int)(InternalEncryptionServer::getState)());
311 server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
312 server.expose(this, "", (std::string)(InternalEncryptionServer::getDevicePath)());
314 server.createNotification("InternalEncryptionServer::mount");
316 std::string source = findDevPath();
318 engine.reset(new INTERNAL_ENGINE(
319 source, INTERNAL_PATH,
320 ProgressBar([](unsigned v) {
321 ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
322 std::to_string(v).c_str());
327 InternalEncryptionServer::~InternalEncryptionServer()
331 int InternalEncryptionServer::setMountPassword(const std::string& password)
333 return keyServer.get(engine->getSource(), password, mountKey);
336 int InternalEncryptionServer::mount()
338 if (mountKey.empty()) {
339 ERROR(SINK, "You need to call set_mount_password() first.");
340 return error::NoData;
343 BinaryData key = mountKey;
346 if (getState() != State::Encrypted) {
347 INFO(SINK, "Cannot mount, SD partition's state incorrect.");
348 return error::NoSuchDevice;
351 if (engine->isMounted()) {
352 INFO(SINK, "Partition already mounted.");
356 INFO(SINK, "Mounting internal storage.");
358 engine->mount(key, getOptions());
360 server.notify("InternalEncryptionServer::mount");
361 } catch (runtime::Exception &e) {
362 ERROR(SINK, "Mount failed: " + std::string(e.what()));
363 return error::Unknown;
369 int InternalEncryptionServer::umount()
371 if (getState() != State::Encrypted) {
372 ERROR(SINK, "Cannot umount, partition's state incorrect.");
373 return error::NoSuchDevice;
376 if (!engine->isMounted()) {
377 INFO(SINK, "Partition already umounted.");
381 INFO(SINK, "Closing all processes using internal storage.");
383 stopDependedSystemdUnits();
384 INFO(SINK, "Umounting internal storage.");
386 } catch (runtime::Exception &e) {
387 ERROR(SINK, "Umount failed: " + std::string(e.what()));
388 return error::Unknown;
394 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
396 if (getState() != State::Unencrypted) {
397 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
398 return error::NoSuchDevice;
401 BinaryData masterKey;
402 int ret = keyServer.get(engine->getSource(), password, masterKey);
403 if (ret != error::None)
406 auto encryptWorker = [masterKey, options, this]() {
408 showProgressUI("encrypt");
411 runtime::File file("/opt/etc/.odeprogress");
412 file.create(MODE_0640);
414 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
415 stopKnownSystemdUnits();
417 std::string source = engine->getSource();
418 auto mntPaths = findMountPointsByDevice(source);
420 if (!mntPaths.empty()) {
421 INFO(SINK, "Closing all processes using internal storage.");
422 stopDependedSystemdUnits();
424 INFO(SINK, "Unmounting internal storage.");
425 unmountInternalStorage(source);
428 INFO(SINK, "Encryption started.");
429 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
430 engine->encrypt(masterKey, options);
431 setOptions(options & getSupportedOptions());
433 INFO(SINK, "Encryption completed.");
434 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
435 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 runtime::File file("/opt/etc/.odeprogress");
471 file.create(MODE_0640);
473 if (engine->isMounted()) {
474 INFO(SINK, "Closing all known systemd services that might be using internal storage.");
475 stopKnownSystemdUnits();
476 INFO(SINK, "Closing all processes using internal storage.");
477 stopDependedSystemdUnits();
479 INFO(SINK, "Umounting internal storage.");
484 } catch (runtime::Exception& e) {
485 stopDependedSystemdUnits();
490 INFO(SINK, "Decryption started.");
491 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
492 engine->decrypt(masterKey, getOptions());
494 INFO(SINK, "Decryption complete.");
495 ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
499 INFO(SINK, "Syncing disk and rebooting.");
501 ::reboot(RB_AUTOBOOT);
502 } catch (runtime::Exception &e) {
503 ERROR(SINK, "Decryption failed: " + std::string(e.what()));
507 std::thread asyncWork(decryptWorker);
513 int InternalEncryptionServer::recovery()
515 int state = getState();
517 if (state == State::Unencrypted)
518 return error::NoSuchDevice;
520 if (state == State::Corrupted)
521 Ext4Tool::mkfs(engine->getSource());
523 runtime::File file("/opt/.factoryreset");
524 file.create(MODE_0640);
528 dbus::Connection& systemDBus = dbus::Connection::getSystem();
529 systemDBus.methodcall("org.tizen.system.deviced",
530 "/Org/Tizen/System/DeviceD/Power",
531 "org.tizen.system.deviced.power",
533 -1, "()", "(si)", "reboot", 0);
534 } catch (runtime::Exception &e) {
535 ::reboot(RB_AUTOBOOT);
540 int InternalEncryptionServer::isPasswordInitialized()
542 return keyServer.isInitialized(engine->getSource());
545 int InternalEncryptionServer::initPassword(const std::string& password)
547 return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
550 int InternalEncryptionServer::cleanPassword(const std::string& password)
552 return keyServer.remove(engine->getSource(), password);
555 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
556 const std::string& newPassword)
558 return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
561 int InternalEncryptionServer::verifyPassword(const std::string& password)
563 return keyServer.verifyPassword(engine->getSource(), password);
566 int InternalEncryptionServer::getState()
568 char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
570 throw runtime::Exception("Failed to get vconf value.");
573 std::string valueStr(value);
576 if (valueStr == "encrypted")
577 return State::Encrypted;
578 else if (valueStr == "unencrypted")
579 return State::Unencrypted;
580 else if (valueStr == "error_partially_encrypted" || valueStr == "error_partially_decrypted")
581 return State::Corrupted;
583 return State::Invalid;
586 unsigned int InternalEncryptionServer::getSupportedOptions()
588 return engine->getSupportedOptions();
591 std::string InternalEncryptionServer::getDevicePath() const
593 return engine->getSource();