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