Print force killed process list for debugging
[platform/core/security/ode.git] / server / internal-encryption.cpp
1 /*
2  *  Copyright (c) 2015-2019 Samsung Electronics Co., Ltd All Rights Reserved
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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
15  */
16 #include <set>
17 #include <algorithm>
18 #include <memory>
19 #include <mutex>
20 #include <condition_variable>
21 #include <list>
22
23 #include <fstream>
24 #include <fcntl.h>
25 #include <signal.h>
26 #include <unistd.h>
27 #include <sys/mount.h>
28 #include <sys/reboot.h>
29 #include <sys/wait.h>
30 #include <limits.h>
31 #include <stdlib.h>
32 #include <string.h>
33
34 #include <vconf.h>
35 #include <tzplatform_config.h>
36 #include <device/power.h>
37 #include <klay/process.h>
38 #include <klay/file-user.h>
39 #include <klay/filesystem.h>
40 #include <klay/dbus/connection.h>
41 #include <klay/dbus/signal.h>
42 #include <klay/error.h>
43 #include <systemd/sd-bus.h>
44
45 #include "misc.h"
46 #include "logger.h"
47 #include "progress-bar.h"
48 #include "rmi/common.h"
49
50 #include "ext4-tool.h"
51 #include "internal-encryption.h"
52 #include "internal-encryption-common.h"
53 #include "upgrade-support.h"
54 #include "file-footer.h"
55
56 namespace ode {
57
58 namespace {
59
60 const char *PRIVILEGE_PLATFORM  = "http://tizen.org/privilege/internal/default/platform";
61 const std::string ODE_OBJECT_PATH = "/Org/Tizen/OnDeviceEncryption";
62 const std::string ODE_INTERFACE_EVENT = "org.tizen.OnDeviceEncryption.Event";
63 const std::string ODE_SIGNAL_NAME = "unmount";
64 const std::string manifest =
65         "<node>"
66         "       <interface name='" + ODE_INTERFACE_EVENT + "'>"
67         "       <signal name='" + ODE_SIGNAL_NAME + "'>"
68         "       </signal>"
69         "       </interface>"
70         "</node>";
71
72 // watches systemd jobs
73 class JobWatch {
74 public:
75         explicit JobWatch(dbus::Connection& systemDBus);
76         ~JobWatch();
77
78         bool waitForJob(const std::string& job);
79
80 private:
81         void jobRemoved(const dbus::Variant& parameters);
82
83         struct Job {
84                 Job(uint32_t id,
85                         const std::string& job,
86                         const std::string& unit,
87                         const std::string& result) : id(id), job(job), unit(unit), result(result) {}
88                 uint32_t id;
89                 std::string job;
90                 std::string unit;
91                 std::string result;
92         };
93
94         dbus::Connection::SubscriptionId id;
95         dbus::Connection& systemDBus;
96         std::list<Job> removedJobs;
97         std::mutex jobsMutex;
98         std::condition_variable jobsCv;
99 };
100
101 JobWatch::JobWatch(dbus::Connection& systemDBus) : systemDBus(systemDBus) {
102         auto callback = [this](dbus::Variant parameters) {
103                 this->jobRemoved(parameters);
104         };
105
106         id = systemDBus.subscribeSignal("",
107                                                                         "/org/freedesktop/systemd1",
108                                                                         "org.freedesktop.systemd1.Manager",
109                                                                         "JobRemoved",
110                                                                         callback);
111 }
112
113 JobWatch::~JobWatch() {
114         systemDBus.unsubscribeSignal(id);
115 }
116
117 bool JobWatch::waitForJob(const std::string& job) {
118         while(true) {
119                 std::unique_lock<std::mutex> lock(jobsMutex);
120                 bool timeout = true;
121                 auto sec = std::chrono::seconds(1);
122                 jobsCv.wait_for(lock, 5*sec, [this, &timeout]{
123                                 if (!removedJobs.empty()) {
124                                         timeout = false;
125                                         return true;
126                                 }
127                                 return false;});
128
129                 if (timeout) {
130                         ERROR(SINK, "job: " + job + ", result: time out");
131                         return false;
132                 }
133
134                 while(!removedJobs.empty()) {
135                         bool match = (removedJobs.front().job == job);
136                         bool done = (removedJobs.front().result == "done");
137                         removedJobs.pop_front();
138                         if (match)
139                                 return done;
140                 }
141         };
142 }
143
144 void JobWatch::jobRemoved(const dbus::Variant& parameters)
145 {
146         uint32_t id;
147         const char* job;
148         const char* unit;
149         const char* result;
150         parameters.get("(uoss)", &id, &job, &unit, &result);
151         WARN(SINK, "id:" + std::to_string(id) + " job:" + job + " unit:" + unit + " result:" + result);
152
153         {
154                 std::lock_guard<std::mutex> guard(jobsMutex);
155                 removedJobs.emplace_back(id, job, unit, result);
156         }
157         jobsCv.notify_one();
158 }
159
160 void stopSystemdUnits()
161 {
162         dbus::Connection& systemDBus = dbus::Connection::getSystem();
163         dbus::VariantIterator iter;
164         std::vector<std::string> preprocessUnits;
165         std::set<std::string> unitsToStop;
166
167         try {
168                 systemDBus.emitSignal("",
169                                                 ODE_OBJECT_PATH,
170                                                 ODE_INTERFACE_EVENT,
171                                                 ODE_SIGNAL_NAME, "()", nullptr);
172         } catch (runtime::Exception &e) {
173                 ERROR(SINK, "Failed to emit signal : " + std::string(e.what()));
174         }
175
176         auto stopUnit = [&systemDBus](const std::string &unit) {
177                 JobWatch watch(systemDBus);
178                 WARN(SINK, "Stopping unit: " + unit);
179                 const char* job = NULL;
180                 try {
181                         systemDBus.methodcall("org.freedesktop.systemd1",
182                                                                         "/org/freedesktop/systemd1",
183                                                                         "org.freedesktop.systemd1.Manager",
184                                                                         "StopUnit",
185                                                                         -1, "(o)", "(ss)", unit.c_str(), "flush").get("(o)", &job);
186                         WARN(SINK, "Waiting for job: " + std::string(job));
187                         if (!watch.waitForJob(job))
188                                 ERROR(SINK, "Stopping unit: " + unit + " failed");
189                 } catch (runtime::Exception &e) {
190                         ERROR(SINK, std::string(e.what()));
191                 }
192         };
193
194         try {
195                 systemDBus.methodcall("org.freedesktop.systemd1",
196                                                                 "/org/freedesktop/systemd1",
197                                                                 "org.freedesktop.systemd1.Manager",
198                                                                 "ListUnits",
199                                                                 -1, "(a(ssssssouso))", "").get("(a(ssssssouso))", &iter);
200         } catch (runtime::Exception &e) {
201                 ERROR(SINK, "Get list of systemd unit : " + std::string(e.what()));
202         }
203
204         while (1) {
205                 unsigned int dataUnit;
206                 char *dataStr[9];
207                 int ret;
208                 ret = iter.get("(ssssssouso)", dataStr, dataStr + 1, dataStr + 2,
209                                                 dataStr + 3, dataStr + 4, dataStr + 5,
210                                                 dataStr + 6, &dataUnit, dataStr + 7, dataStr + 8);
211                 if (!ret)
212                         break;
213
214                 std::string unitName(dataStr[0]);
215                 if (unitName == "security-manager.socket" ||
216                                 unitName == "connman.socket" ||
217                                 unitName == "msg-server.socket") {
218                         preprocessUnits.insert(preprocessUnits.begin(), unitName);
219                 } else if (unitName.compare(0, 5, "user@") == 0 ||
220                                 unitName == "tlm.service" ||
221                                 unitName == "resourced.service" ||
222                                 unitName == "security-manager.service") {
223                         preprocessUnits.push_back(unitName);
224                 }
225         }
226
227         for (auto unit : preprocessUnits) {
228                 stopUnit(unit);
229         }
230
231         for (pid_t pid : runtime::FileUser::getList(INTERNAL_PATH, true)) {
232                 auto pgid = ::getpgid(pid);
233                 if (pgid > 0 && pid != pgid) {
234                         WARN(SINK, "PGID doesn't match - pgid : " + std::to_string(pgid) + ", pid : " + std::to_string(pid));
235                         continue;
236                 }
237
238                 try {
239                         char *unit = nullptr;
240                         systemDBus.methodcall("org.freedesktop.systemd1",
241                                                                         "/org/freedesktop/systemd1",
242                                                                         "org.freedesktop.systemd1.Manager",
243                                                                         "GetUnitByPID",
244                                                                         -1, "(o)", "(u)", (unsigned int)pid)
245                                                                                 .get("(o)", &unit);
246
247                         char* tmp  = NULL;
248                         int err = sd_bus_path_decode(unit, "/org/freedesktop/systemd1/unit", &tmp);
249                         if (err <= 0 || tmp == NULL) {
250                                 ERROR(SINK, "Failed to decode unit name: " + std::string(unit) + " error: " +
251                                             std::to_string(err));
252                                 continue;
253                         }
254                         std::string unescapedName(tmp);
255                         free(tmp);
256
257                         unitsToStop.insert(unescapedName);
258                 } catch (runtime::Exception &e) {
259                         ERROR(SINK, "Killing process: " + std::to_string(pid));
260                         ::kill(pid, SIGKILL);
261                 }
262         }
263
264         for (auto unit : unitsToStop) {
265                 stopUnit(unit);
266         }
267 }
268
269 void showProgressUI(const std::string type)
270 {
271         dbus::Connection& systemDBus = dbus::Connection::getSystem();
272         std::string unit("ode-progress-ui@"+type+".service");
273
274         JobWatch watch(systemDBus);
275         INFO(SINK, "Start unit: " + unit);
276
277         const char* job = NULL;
278         systemDBus.methodcall("org.freedesktop.systemd1",
279                                                         "/org/freedesktop/systemd1",
280                                                         "org.freedesktop.systemd1.Manager",
281                                                         "StartUnit",
282                                                         -1, "(o)", "(ss)", unit.c_str(), "replace").get("(o)", &job);
283
284         INFO(SINK, "Waiting for job: " + std::string(job));
285         if (!watch.waitForJob(job))
286                 ERROR(SINK, "Starting unit: " + unit + " failed");
287 }
288
289 unsigned int getOptions()
290 {
291         unsigned int result = 0;
292         int value;
293
294         value = 0;
295         ::vconf_get_bool(VCONFKEY_ODE_FAST_ENCRYPTION, &value);
296         if (value) {
297                 result |= InternalEncryption::Option::IncludeUnusedRegion;
298         }
299
300         return result;
301 }
302
303 void setOptions(unsigned int options)
304 {
305         bool value;
306
307         if (options & InternalEncryption::Option::IncludeUnusedRegion) {
308                 value = true;
309         } else {
310                 value = false;
311         }
312         ::vconf_set_bool(VCONFKEY_ODE_FAST_ENCRYPTION, value);
313 }
314
315 void killProcesses(std::vector<const char*> &args)
316 {
317         int pipeFd[2] = {0, };
318         pid_t pid = 0;
319
320         if (::pipe(pipeFd) < 0)
321                 throw runtime::Exception("Failed to create pipe");
322
323         pid = ::fork();
324         if (pid < 0) {
325                 ::close(pipeFd[0]);
326                 ::close(pipeFd[1]);
327                 throw runtime::Exception("Failed to fork");
328         }
329
330         if (pid == 0) {
331                 ::close(pipeFd[0]);
332                 if (::dup2(pipeFd[1], STDOUT_FILENO) < 0)
333                         ERROR(SINK, "Failed to copy STDOUT_FILENO");
334
335                 if (::dup2(STDOUT_FILENO, STDERR_FILENO) < 0)
336                         ERROR(SINK, "Failed to copy STDERR_FILENO");
337
338                 ::close(pipeFd[1]);
339
340                 if (::execv(args[0], const_cast<char* const*>(args.data())) < 0)
341                         ERROR(SINK, "Failed to execute : " + std::to_string(errno));
342
343                 std::quick_exit(EXIT_FAILURE);
344         }
345
346         ::close(pipeFd[1]);
347
348         for (int status = 0; ::waitpid(pid, &status, 0) == -1;) {
349                 if (errno != EINTR) {
350                         ::close(pipeFd[0]);
351                         throw runtime::Exception("Failed to wait child process");
352                 }
353         }
354
355         auto closeFile = [](FILE *fp) { ::fclose(fp); };
356         std::unique_ptr<FILE, decltype(closeFile)> fp(::fdopen(pipeFd[0], "r"), closeFile);
357         if (fp == nullptr) {
358                 ::close(pipeFd[0]);
359                 throw runtime::Exception("Failed to open pipe descriptor");
360         }
361
362         char *line = nullptr;
363         size_t len = 0;
364         try {
365                 while ((::getline(&line, &len, fp.get())) != -1) {
366                         std::string log(line);
367                         log.erase(std::find_if(log.rbegin(), log.rend(),
368                                                 std::ptr_fun<int, int>(std::isgraph)).base(), log.end());
369                         WARN(SINK, log);
370                 }
371         } catch (std::exception &e) {
372                 ERROR(SINK, e.what());
373         }
374         ::free(line);
375         ::close(pipeFd[0]);
376 }
377
378 bool isPartitionTerminated(const std::string &partition)
379 {
380         bool ret = true;
381         const std::string cmd("fuser -m " + partition + " | grep -o '[0-9]*'");
382         char *line = nullptr;
383         size_t len = 0;
384
385         FILE *fp = ::popen(cmd.c_str(), "r");
386         if (fp == nullptr) {
387                 ERROR(SINK, "Failed to get processes on partition");
388                 return false;
389         }
390
391         if (::getline(&line, &len, fp) != -1)
392                 ret = false;
393
394         ::free(line);
395         ::pclose(fp);
396
397         return ret;
398 }
399
400 void unmountInternalStorage(const std::string& source)
401 {
402         if (::umount2("/opt/usr", MNT_DETACH) == -1) {
403                 if (errno != EBUSY && errno != EINVAL) {
404                         throw runtime::Exception("umount() error : " + runtime::GetSystemErrorMessage());
405                 }
406         }
407
408         do {
409                 ::sync();
410                 std::vector<const char*> args = {
411                         "/usr/bin/fuser", "-m", "-k", "-v", "-SIGTERM", source.c_str(), nullptr
412                 };
413                 try {
414                         killProcesses(args);
415                         ::usleep((useconds_t)((unsigned int)(500)*1000));
416
417                         args[4] = "-SIGKILL";
418                         killProcesses(args);
419                         ::usleep((useconds_t)((unsigned int)(200)*1000));
420                 } catch (runtime::Exception &e) {
421                         ERROR(e.what());
422                 }
423         } while (!isPartitionTerminated(source));
424 }
425
426 }
427
428 InternalEncryptionServer::InternalEncryptionServer(ServerContext& srv,
429                                                                                                    KeyServer& key) :
430         server(srv),
431         keyServer(key)
432 {
433         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::setMountPassword)(std::string));
434         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::mount)(std::vector<unsigned char>, unsigned int));
435         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::umount)());
436         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::isMounted)());
437         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::encrypt)(std::string, unsigned int));
438         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::decrypt)(std::string));
439         server.expose(this, "", (int)(InternalEncryptionServer::isPasswordInitialized)());
440         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::recovery)());
441         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::initPassword)(std::string));
442         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::cleanPassword)(std::string));
443         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::changePassword)(std::string, std::string));
444         server.expose(this, PRIVILEGE_PLATFORM, (int)(InternalEncryptionServer::verifyPassword)(std::string));
445         server.expose(this, "", (int)(InternalEncryptionServer::getState)());
446         server.expose(this, "", (unsigned int)(InternalEncryptionServer::getSupportedOptions)());
447         server.expose(this, "", (std::string)(InternalEncryptionServer::getDevicePath)());
448
449         server.createNotification("InternalEncryptionServer::mount");
450
451         std::string source = findDevPath();
452
453         if (getState() == State::Encrypted) {
454                 //"error_partially_encrypted"
455                 if (!FileFooter::exist(source) && !UpgradeSupport::checkUpgradeFlag()) {
456                         // Trigger key migration process
457                         UpgradeSupport::createUpgradeFlag();
458                 }
459         }
460
461         engine.reset(new INTERNAL_ENGINE(
462                 source, INTERNAL_PATH,
463                 ProgressBar([](int v) {
464                         ::vconf_set_str(VCONFKEY_ODE_ENCRYPT_PROGRESS,
465                                                         std::to_string(v).c_str());
466                 })
467         ));
468
469         try {
470                 dbus::Connection &systemDBus = dbus::Connection::getSystem();
471                 systemDBus.registerObject(ODE_OBJECT_PATH, manifest, nullptr, nullptr);
472         } catch (runtime::Exception &e) {
473                 ERROR(SINK, e.what());
474         }
475 }
476
477 InternalEncryptionServer::~InternalEncryptionServer()
478 {
479 }
480
481 int InternalEncryptionServer::migrateMasterKey(const std::string& dev, const std::string& password)
482 {
483         try {
484                 BinaryData masterKey = UpgradeSupport::loadMasterKey(dev);
485
486                 // encrypt the master key with given password
487                 return keyServer.changePassword2(dev, masterKey, password);
488         } catch (const runtime::Exception&) {
489                 ERROR(SINK, "Failed to load the master key stored during upgrade.");
490         }
491
492         return error::Unknown;
493 }
494
495 int InternalEncryptionServer::setMountPassword(const std::string& password)
496 {
497         const std::string& dev = engine->getSource();
498
499         // check if upgrade flag exists
500         if (UpgradeSupport::checkUpgradeFlag()) {
501                 INFO(SINK, "Upgrade flag detected.");
502
503                 int rc = migrateMasterKey(dev, password);
504                 if (rc != error::None)
505                         return rc;
506                 UpgradeSupport::removeUpgradeFlag();
507         }
508
509         return keyServer.get(dev, password, mountKey);
510 }
511
512 int InternalEncryptionServer::mount(const std::vector<unsigned char> &mk, unsigned int options)
513 {
514         if (mountKey.empty() && mk.empty()) {
515                 ERROR(SINK, "You need to set master key first.");
516                 return error::NoData;
517         }
518
519         BinaryData key = mk.empty() ? mountKey : mk;
520         mountKey.clear();
521
522         if (getState() != State::Encrypted) {
523                 ERROR(SINK, "Cannot mount, SD partition's state incorrect.");
524                 return error::NoSuchDevice;
525         }
526
527         if (engine->isMounted()) {
528                 ERROR(SINK, "Partition already mounted.");
529                 return error::None;
530         }
531
532         INFO(SINK, "Mounting internal storage.");
533         try {
534                 engine->mount(key, getOptions());
535
536                 server.notify("InternalEncryptionServer::mount");
537
538                 runtime::File("/tmp/.lazy_mount").create(O_WRONLY);
539                 runtime::File("/tmp/.unlock_mnt").create(O_WRONLY);
540         } catch (runtime::Exception &e) {
541                 ERROR(SINK, "Mount failed: " + std::string(e.what()));
542                 return error::Unknown;
543         }
544
545         return error::None;
546 }
547
548 int InternalEncryptionServer::isMounted()
549 {
550         int ret = 0;
551         try {
552                 ret = engine->isMounted() ? 1 : 0;
553         } catch (runtime::Exception &e) {
554                 ERROR(SINK, "Failed to access the mount flag");
555                 return error::Unknown;
556         }
557         return ret;
558 }
559
560 int InternalEncryptionServer::umount()
561 {
562         if (getState() != State::Encrypted) {
563                 ERROR(SINK, "Cannot umount, partition's state incorrect.");
564                 return error::NoSuchDevice;
565         }
566
567         if (!engine->isMounted()) {
568                 ERROR(SINK, "Partition already umounted.");
569                 return error::None;
570         }
571
572         INFO(SINK, "Closing all processes using internal storage.");
573         try {
574                 stopSystemdUnits();
575                 INFO(SINK, "Umounting internal storage.");
576                 unmountInternalStorage("/dev/mapper/userdata");
577                 engine->umount();
578         } catch (runtime::Exception &e) {
579                 ERROR(SINK, "Umount failed: " + std::string(e.what()));
580                 return error::Unknown;
581         }
582
583         return error::None;
584 }
585
586 int InternalEncryptionServer::encrypt(const std::string& password, unsigned int options)
587 {
588         if (getState() != State::Unencrypted) {
589                 ERROR(SINK, "Cannot encrypt, partition's state incorrect.");
590                 return error::NoSuchDevice;
591         }
592
593         BinaryData masterKey;
594         int ret = keyServer.get(engine->getSource(), password, masterKey);
595         if (ret != error::None)
596                 return ret;
597
598         auto encryptWorker = [masterKey, options, this]() {
599                 try {
600                         if (::device_power_request_lock(POWER_LOCK_DISPLAY, 0) != 0)
601                                 ERROR(SINK, "Failed to request to lock display");
602
603                         showProgressUI("encrypt");
604                         ::sleep(1);
605
606                         runtime::File file("/opt/etc/.odeprogress");
607                         file.create(0640);
608
609                         std::string source = engine->getSource();
610                         auto mntPaths = findMountPointsByDevice(source);
611
612                         if (!mntPaths.empty()) {
613                                 INFO(SINK, "Closing all processes using internal storage.");
614                                 stopSystemdUnits();
615
616                                 INFO(SINK, "Unmounting internal storage.");
617                                 unmountInternalStorage(source);
618                         }
619
620                         INFO(SINK, "Encryption started.");
621                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_encrypted");
622                         try {
623                                 engine->encrypt(masterKey, options);
624                         } catch (runtime::Exception &e) {
625                                 ERROR(SINK, e.what());
626                                 if (!engine->isStarted()) {
627                                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
628                                         file.remove();
629                                 }
630                                 ::sync();
631                                 ::reboot(RB_AUTOBOOT);
632                         }
633                         setOptions(options & getSupportedOptions());
634
635                         INFO(SINK, "Encryption completed.");
636                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
637                         server.notify("InternalEncryptionServer::mount");
638
639                         file.remove();
640
641                         INFO(SINK, "Syncing disk and rebooting.");
642                         ::sync();
643                         ::reboot(RB_AUTOBOOT);
644                 } catch (runtime::Exception &e) {
645                         ERROR(SINK, "Encryption failed: " + std::string(e.what()));
646                 }
647         };
648
649         std::thread asyncWork(encryptWorker);
650         asyncWork.detach();
651
652         return error::None;
653 }
654
655 int InternalEncryptionServer::decrypt(const std::string& password)
656 {
657         if (getState() != State::Encrypted) {
658                 ERROR(SINK, "Cannot decrypt, partition's state incorrect.");
659                 return error::NoSuchDevice;
660         }
661
662         // check if key migration is needed
663         if (UpgradeSupport::checkUpgradeFlag()) {
664                 INFO(SINK, "Upgrade flag detected.");
665                 const std::string& dev = engine->getSource();
666                 int rc = migrateMasterKey(dev, password);
667                 if (rc == error::None)
668                         UpgradeSupport::removeUpgradeFlag();
669         }
670
671         BinaryData masterKey;
672         int ret = keyServer.get(engine->getSource(), password, masterKey);
673         if (ret != error::None)
674                 return ret;
675
676         auto decryptWorker = [masterKey, this]() {
677                 try {
678                         if (::device_power_request_lock(POWER_LOCK_DISPLAY, 0) != 0)
679                                 ERROR(SINK, "Failed to request to lock display");
680
681                         showProgressUI("decrypt");
682                         ::sleep(1);
683
684                         runtime::File file("/opt/etc/.odeprogress");
685                         file.create(0640);
686
687                         if (engine->isMounted()) {
688                                 INFO(SINK, "Closing all processes using internal storage.");
689                                 stopSystemdUnits();
690
691                                 INFO(SINK, "Umounting internal storage.");
692                                 unmountInternalStorage("/dev/mapper/userdata");
693                                 engine->umount();
694                         }
695
696                         INFO(SINK, "Decryption started.");
697                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "error_partially_decrypted");
698                         try {
699                                 engine->decrypt(masterKey, getOptions());
700                         } catch (runtime::Exception &e) {
701                                 ERROR(SINK, e.what());
702                                 if (!engine->isStarted()) {
703                                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "encrypted");
704                                         file.remove();
705                                 }
706                                 ::sync();
707                                 ::reboot(RB_AUTOBOOT);
708                         }
709
710                         INFO(SINK, "Decryption complete.");
711                         ::vconf_set_str(VCONFKEY_ODE_CRYPTO_STATE, "unencrypted");
712
713                         file.remove();
714
715                         INFO(SINK, "Syncing disk and rebooting.");
716                         ::sync();
717                         ::reboot(RB_AUTOBOOT);
718                 } catch (runtime::Exception &e) {
719                         ERROR(SINK, "Decryption failed: " + std::string(e.what()));
720                 }
721         };
722
723         std::thread asyncWork(decryptWorker);
724         asyncWork.detach();
725
726         return error::None;
727 }
728
729 int InternalEncryptionServer::recovery()
730 {
731         int state = getState();
732
733         if (state == State::Unencrypted)
734                 return error::NoSuchDevice;
735
736         runtime::File file("/opt/.factoryreset");
737         file.create(0640);
738
739         ::sync();
740         try {
741                 dbus::Connection& systemDBus = dbus::Connection::getSystem();
742                 systemDBus.methodcall("org.tizen.system.deviced",
743                                                                 "/Org/Tizen/System/DeviceD/Power",
744                                                                 "org.tizen.system.deviced.power",
745                                                                 "reboot",
746                                                                 -1, "()", "(si)", "reboot", 0);
747         } catch (runtime::Exception &e) {
748                 ::reboot(RB_AUTOBOOT);
749         }
750         return error::None;
751 }
752
753 int InternalEncryptionServer::isPasswordInitialized()
754 {
755         return keyServer.isInitialized(engine->getSource());
756 }
757
758 int InternalEncryptionServer::initPassword(const std::string& password)
759 {
760         return keyServer.init(engine->getSource(), password, Key::DEFAULT_256BIT);
761 }
762
763 int InternalEncryptionServer::cleanPassword(const std::string& password)
764 {
765         return keyServer.remove(engine->getSource(), password);
766 }
767
768 int InternalEncryptionServer::changePassword(const std::string& oldPassword,
769                                                                                 const std::string& newPassword)
770 {
771         return keyServer.changePassword(engine->getSource(), oldPassword, newPassword);
772 }
773
774 int InternalEncryptionServer::verifyPassword(const std::string& password)
775 {
776         return keyServer.verifyPassword(engine->getSource(), password);
777 }
778
779 int InternalEncryptionServer::getState()
780 {
781         char *value = ::vconf_get_str(VCONFKEY_ODE_CRYPTO_STATE);
782         if (value == NULL) {
783                 throw runtime::Exception("Failed to get vconf value.");
784         }
785
786         std::string valueStr(value);
787         free(value);
788
789         if (valueStr == "encrypted")
790                 return State::Encrypted;
791         else if (valueStr == "unencrypted")
792                 return State::Unencrypted;
793         else if (valueStr == "error_partially_encrypted" || valueStr == "error_partially_decrypted")
794                 return State::Corrupted;
795
796         return State::NotSupported;
797 }
798
799 unsigned int InternalEncryptionServer::getSupportedOptions()
800 {
801         return engine->getSupportedOptions();
802 }
803
804 std::string InternalEncryptionServer::getDevicePath() const
805 {
806         return engine->getSource();
807 }
808
809 } // namespace ode